diff --git a/Applications/Finder/Finder.lua b/Applications/Finder/Finder.lua index d5e54fb3..1d9ddf4a 100644 --- a/Applications/Finder/Finder.lua +++ b/Applications/Finder/Finder.lua @@ -1,16 +1,20 @@ +-- package.loaded.MineOSCore = nil +-- _G.MineOSCore = nil -- Адаптивная загрузка необходимых библиотек и компонентов local libraries = { - ["component"] = "component", - ["computer"] = "computer", - ["event"] = "event", - ["fs"] = "filesystem", - ["files"] = "files", - ["context"] = "context", - ["unicode"] = "unicode", - ["buffer"] = "doubleBuffering", - ["archive"] = "archive", - ["serialization"] = "serialization", + buffer = "doubleBuffering", + MineOSCore = "MineOSCore", + component = "component", + computer = "computer", + event = "event", + fs = "filesystem", + files = "files", + context = "context", + unicode = "unicode", + archive = "archive", + serialization = "serialization", + GUI = "GUI", } local components = { @@ -27,221 +31,213 @@ local colors = { topBar = 0xdddddd, main = 0xffffff, leftBar = 0xeeeeee, + leftBarTransparency = 35, leftBarSelection = ecs.colors.blue, - closes = {cross = ecs.colors.red, hide = ecs.colors.orange, full = ecs.colors.green}, + leftBarSelectionText = 0xFFFFFF, + closes = {close = ecs.colors.red, hide = ecs.colors.orange, full = ecs.colors.green}, topText = 0x262626, topButtons = 0xffffff, topButtonsText = 0x262626, leftBarHeader = 0x000000, leftBarList = 0x444444, selection = 0x555555, + mainScrollBarPipe = 0x999999, } -local leftBar local pathToConfig = "MineOS/System/Finder/Config.cfg" local lang = files.loadTableFromFile("MineOS/System/OS/Languages/" .. _G.OSSettings.language .. ".lang") local workPathHistory = {} local currentWorkPathHistoryElement = 1 -local x, y, width, height, yEnd, xEnd, heightOfTopBar, widthOfLeftBar, heightOfLeftBar, yLeftBar, widthOfMain, xMain -local widthOfBottom, widthOfIcon, heightOfIcon, xSpaceBetweenIcons, ySpaceBetweenIcons, xCountOfIcons, yCountOfIcons -local fileList, fromLine, fromLineLeftBar = nil, 1, 1 -local showSystemFiles, showHiddenFiles, showFileFormat -local oldPixelsOfFullScreen -local isFullScreen -local sortingMethods = { - {name = "type", symbol = lang.sortByTypeShort}, - {name = "name", symbol = lang.sortByNameShort}, - {name = "date", symbol = lang.sortByDateShort}, -} -local currentSortingMethod = 1 +local oldPixelsOfFullScreen, isFullScreen +local scrollSpeed = 2 +local searchBarText + +local disks = {} +local sizes = {} +local fileList = {} +local config = {} +local obj = {} +local sortingMethods = {[0] = lang.sortByTypeShort, [1] = lang.sortByNameShort, [2] = lang.sortByDateShort, [lang.sortByTypeShort] = 0, [lang.sortByNameShort] = 1, [lang.sortByDateShort] = 2} ------------------------------------------------------------------------------------------------------------------ --Сохраняем все настроечки вот тут вот local function saveConfig() - fs.makeDirectory(fs.path(pathToConfig)) - local file = io.open(pathToConfig, "w") - file:write(serialization.serialize( { ["leftBar"] = leftBar, ["showHiddenFiles"] = showHiddenFiles, ["showSystemFiles"] = showSystemFiles, ["showFileFormat"] = showFileFormat, ["currentSortingMethod"] = currentSortingMethod })) - file:close() + files.saveTableToFile(pathToConfig, config) end --Загрузка конфига local function loadConfig() if fs.exists(pathToConfig) then - local file = io.open(pathToConfig, "r") - local readedConfig = file:read("*a") - file:close() - readedConfig = serialization.unserialize(readedConfig) - leftBar = readedConfig.leftBar - showFileFormat = readedConfig.showFileFormat - showSystemFiles = readedConfig.showSystemFiles - showHiddenFiles = readedConfig.showHiddenFiles - currentSortingMethod = readedConfig.currentSortingMethod + config = files.loadTableFromFile(pathToConfig) else - leftBar = { - {"Title", "Избранное"}, - {"Element", "Root", ""}, - {"Element", "System", "MineOS/System/"}, - {"Element", "Libraries", "lib/"}, - {"Element", "Scripts", "bin/"}, - {"Element", "Desktop", "MineOS/Desktop/"}, - {"Element", "Applications", "MineOS/Applications/"}, - {"Element", "Pictures", "MineOS/Pictures/"}, - {"Title", "", ""}, - {"Title", "Диски"}, + config.favourites = { + {name = "Root", path = ""}, + {name = "System", path = "MineOS/System/"}, + {name = "Libraries", path = "lib/"}, + {name = "Scripts", path = "bin/"}, + {name = "Desktop", path = "MineOS/Desktop/"}, + {name = "Applications", path = "MineOS/Applications/"}, + {name = "Pictures", path = "MineOS/Pictures/"}, } - showFileFormat = false - showSystemFiles = false - showHiddenFiles = false - currentSortingMethod = 1 + config.showFileFormat = false + config.showSystemFiles = false + config.showHiddenFiles = false + config.currentSortingMethod = 0 saveConfig() end end ---СОЗДАНИЕ ОБЪЕКТОВ -local obj = {} -local function newObj(class, name, ...) - obj[class] = obj[class] or {} - obj[class][name] = {...} -end - --Создание дисков для лефтбара local function createDisks() local HDDs = ecs.getHDDs() - + disks = {} for proxy, path in fs.mounts() do for i = 1, #HDDs do if proxy.address == HDDs[i].address and path ~= "/" then - table.insert(leftBar, {"Element", fs.name(path), unicode.sub(path, 2, -1)}) - --ecs.error("path = "..path) + table.insert(disks, {path = fs.name(path), name = unicode.sub(path, 2, -1)}) end end end end ---Короч такая хуйня, смари. Сначала оно удаляет все диски ---А затем их создает заново -local function chkdsk() - local position = #leftBar - while true do - if leftBar[position][1] == "Title" then break end - --Анализ - table.remove(leftBar, position) - --Постанализ - position = position - 1 - end - - fromLineLeftBar = 1 - createDisks() -end - --Получить файловый список -local function getFileList(path) - fileList = ecs.getFileList(path) - fileList = ecs.sortFiles(path, fileList, sortingMethods[currentSortingMethod].name, showHiddenFiles) +local function getFileList() + fileList = ecs.getFileList(workPathHistory[currentWorkPathHistoryElement]) + fileList = ecs.sortFiles(workPathHistory[currentWorkPathHistoryElement], fileList, config.currentSortingMethod, config.showHiddenFiles) + if searchBarText then fileList = ecs.searchInArray(fileList, searchBarText) end end --Перейти в какую-то папку local function changePath(path) - --Очищаем все элементы, следующие за текущим for i = currentWorkPathHistoryElement, #workPathHistory do table.remove(workPathHistory, currentWorkPathHistoryElement + 1) end - --Вставляем новый элементик нового пути + + sizes.yFileList = sizes.yFileListStartPoint + searchBarText = nil + table.insert(workPathHistory, path) - --На всякий - fromLine = 1 - --Текущий элемент равен последнему currentWorkPathHistoryElement = #workPathHistory - --Получаем список файлов текущей директории - getFileList(workPathHistory[currentWorkPathHistoryElement]) + + getFileList() end --Считаем размеры всего local function calculateSizes() - heightOfTopBar = 3 - widthOfLeftBar = 16 - heightOfLeftBar = height - heightOfTopBar - heightOfMain = heightOfLeftBar - 1 - yLeftBar = y + heightOfTopBar - widthOfMain = width - widthOfLeftBar - 1 - widthOfBottom = width - widthOfLeftBar - xMain = x + widthOfLeftBar - yEnd = y + height - 1 - xEnd = x + width - 1 - widthOfIcon = 12 - heightOfIcon = 6 - xSpaceBetweenIcons = 1 - ySpaceBetweenIcons = 1 - xCountOfIcons = math.floor(widthOfMain / (widthOfIcon + xSpaceBetweenIcons)) - yCountOfIcons = math.floor(heightOfLeftBar / (heightOfIcon + ySpaceBetweenIcons)) - maxCountOfIcons = xCountOfIcons * yCountOfIcons + sizes.xSpaceBetweenIcons, sizes.ySpaceBetweenIcons = 2, 1 + sizes.finderWidth, sizes.finderHeight = math.floor(buffer.screen.width * 0.585), math.floor(buffer.screen.height * 0.52) + sizes.leftBarWidth = math.floor(sizes.finderWidth * 0.22) + sizes.topBarHeight = 3 + sizes.mainWidth, sizes.mainHeight = sizes.finderWidth - sizes.leftBarWidth - 1, sizes.finderHeight - sizes.topBarHeight - 1 + sizes.xFinder, sizes.yFinder = math.floor(buffer.screen.width / 2 - sizes.finderWidth / 2), math.floor(buffer.screen.height / 2 - sizes.finderHeight / 2) + sizes.xFinderEnd, sizes.yFinderEnd = sizes.xFinder + sizes.finderWidth - 1, sizes.yFinder + sizes.finderHeight - 1 + sizes.xMain, sizes.yMain = sizes.xFinder + sizes.leftBarWidth, sizes.yFinder + sizes.topBarHeight + sizes.xCountOfIcons, sizes.yCountOfIcons, sizes.totalCountOfIcons = MineOSCore.getParametersForDrawingIcons(sizes.mainWidth - 4, sizes.mainHeight, sizes.xSpaceBetweenIcons, sizes.ySpaceBetweenIcons) + sizes.yFileListStartPoint = sizes.yMain + 1 + sizes.yFileList = sizes.yFileListStartPoint + sizes.iconTotalHeight = MineOSCore.iconHeight + sizes.ySpaceBetweenIcons + sizes.searchBarWidth = math.floor(sizes.finderWidth * 0.21) + sizes.xSearchBar = sizes.xFinderEnd - sizes.searchBarWidth - 1 + obj.mainZone = GUI.object(sizes.xMain, sizes.yMain, sizes.mainWidth, sizes.mainHeight) end --Рисем цветные кружочки слева вверху local function drawCloses() - local symbol = "⬤" - buffer.set(x + 1, y, colors.topBar, colors.closes.cross, symbol) - buffer.set(x + 3, y, colors.topBar, colors.closes.hide, symbol) - buffer.set(x + 5, y, colors.topBar, colors.closes.full, symbol) - newObj("Closes", 1, x + 1, y, x + 2, y) - newObj("Closes", 2, x + 3, y, x + 4, y) - newObj("Closes", 3, x + 5, y, x + 6, y) + local x, y = sizes.xFinder + 1, sizes.yFinder + local symbol = "●" + obj.close = GUI.button(x, y, 1, 1, colors.topBar, colors.closes.close, colors.topBar, 0x000000, symbol) + obj.hide = GUI.button(obj.close.x + obj.close.width + 1, y, 1, 1, colors.topBar, colors.closes.hide, colors.topBar, 0x000000, symbol) + obj.full = GUI.button(obj.hide.x + obj.hide.width + 1, y, 1, 1, colors.topBar, colors.closes.full, colors.topBar, 0x000000, symbol) end ---Рисуем строку поиска -local function drawSearch() - local limit = width * 1 / 4 - ecs.inputText(x + width - limit - 1, y + 1, limit, " Поиск", colors.topButtons, 0x999999, true) +local function drawSearchBar(justDrawNotEvent) + local y = sizes.yFinder + 1 + local textColor = searchBarText and 0x262626 or 0xBBBBBB + obj.search = GUI.object(sizes.xSearchBar, y, sizes.searchBarWidth, 1) + buffer.square(sizes.xSearchBar, y, sizes.searchBarWidth, 1, 0xFFFFFF, textColor, " ") + return GUI.input(sizes.xSearchBar + 1, y, sizes.searchBarWidth - 2, textColor, searchBarText or lang.search, {justDrawNotEvent = justDrawNotEvent}) end -local function drawFsControl() - obj["FSButtons"] = {} - local xPos, yPos = xMain, y + 1 - local name, fg, bg - - local function getColors(cyka) - if cyka then return 0x262626, 0xffffff else return 0xffffff, 0x262626 end - end - - for i = 1, #sortingMethods do - name = sortingMethods[i].symbol; bg, fg = getColors(currentSortingMethod == i); newObj("FSButtons", i, buffer.button(xPos, yPos, unicode.len(name) + 2, 1, bg, fg, name)); xPos = xPos + unicode.len(name) + 3 - end - --xPos = xPos + 4 - name = lang.showFileFormatShort; bg, fg = getColors(showFileFormat); newObj("FSButtons", #sortingMethods + 1, buffer.button(xPos, yPos, unicode.len(name) + 2, 1, bg, fg, name)); xPos = xPos + unicode.len(name) + 3 - name = lang.showHiddenFilesShort; bg, fg = getColors(showHiddenFiles); newObj("FSButtons", #sortingMethods + 2, buffer.button(xPos, yPos, unicode.len(name) + 2, 1, bg, fg, name)); xPos = xPos + unicode.len(name) + 3 - - -- name = lang.showFileFormatShort; newObj("FSButtons", 1, buffer.adaptiveButton(xPos, yPos, 1, 0, getColors(showFileFormat), name)); xPos = xPos + unicode.len(name) + 3 - -- name = lang.showHiddenFilesShort; newObj("FSButtons", 2, buffer.adaptiveButton(xPos, yPos, 1, 0, getColors(showHiddenFiles), name)); xPos = xPos + unicode.len(name) + 3 - -- name = "Системные"; newObj("FSButtons", 3, buffer.adaptiveButton(xPos, yPos, 1, 0, getColors(showSystemFiles), name)); xPos = xPos + unicode.len(name) + 3 -end - ---Рисуем верхнюю часть local function drawTopBar() - --Рисуем сам бар - buffer.square(x, y, width, heightOfTopBar, colors.topBar, 0xffffff, " ") - --Рисуем кнопочки + buffer.square(sizes.xFinder, sizes.yFinder, sizes.finderWidth, sizes.topBarHeight, colors.topBar) drawCloses() - --Рисуем титл - -- local text = workPathHistory[currentWorkPathHistoryElement] or "Root" - -- ecs.colorText(x + math.floor(width / 2 - unicode.len(text) / 2), y, colors.topText, text) - --Рисуем кнопочки влево-вправо - local xPos, yPos = x + 1, y + 1 - name = "<"; newObj("TopButtons", name, buffer.button(xPos, yPos, 3, 1, colors.topButtons, colors.topButtonsText, name)) - xPos = xPos + 4 - name = ">"; newObj("TopButtons", name, buffer.button(xPos, yPos, 3, 1, colors.topButtons, colors.topButtonsText, name)) - --Поиск рисуем - --drawSearch() - --Кнопочки контроля файловой системы рисуем - drawFsControl() + local x, y = sizes.xFinder + 2, sizes.yFinder + 1 + obj.historyBack = GUI.button(x, y, 3, 1, 0xffffff, 0x262626, 0xAAAAAA, 0x000000, "<"); x = x + obj.historyBack.width + 1 + obj.historyForward = GUI.button(x, y, 3, 1, 0xffffff, 0x262626, 0xAAAAAA, 0x000000, ">"); x = x + obj.historyForward.width + 2 + + local cyka = { + {objName = "sortingMethod", text = sortingMethods[config.currentSortingMethod], active = false}, + {objName = "showFormat", text = lang.showFileFormatShort, active = config.showFileFormat}, + {objName = "showHidden", text = lang.showHiddenFilesShort, active = config.showHiddenFiles}, + } + for i = 1, #cyka do + obj[cyka[i].objName] = GUI.adaptiveButton(x, y, 1, 0, 0xFFFFFF, 0x262626, 0x262626, 0xFFFFFF, cyka[i].text) + if cyka[i].active then obj[cyka[i].objName]:draw(true) end + x = x + obj[cyka[i].objName].width + 1 + end + + drawSearchBar(true) +end + +local function drawAndHiglightPath(y, arrayElement) + -- GUI.error(workPathHistory[currentWorkPathHistoryElement] .. " - " .. tostring(arrayElement.path)) + local pathAreEquals = workPathHistory[currentWorkPathHistoryElement] == arrayElement.path + if pathAreEquals then buffer.square(sizes.xFinder, y, sizes.leftBarWidth, 1, colors.leftBarSelection, colors.leftBarSelectionText, " ") end + buffer.text(sizes.xFinder + 2, y, pathAreEquals and colors.leftBarSelectionText or colors.leftBarList, unicode.sub(arrayElement.name, 1, sizes.leftBarWidth - 4)) + local object = GUI.object(sizes.xFinder, y, sizes.leftBarWidth, 1) + object.path = arrayElement.path + table.insert(obj.leftBarItems, object) +end + +local function drawLeftBar() + obj.leftBarItems = {} + buffer.setDrawLimit(sizes.xFinder, sizes.yMain, sizes.leftBarWidth, sizes.mainHeight + 1) + buffer.paste(1, 1, oldPixelsOfFullScreen) + buffer.square(sizes.xFinder, sizes.yMain, sizes.leftBarWidth, sizes.mainHeight + 1, colors.leftBar, 0x000000, " ", colors.leftBarTransparency) + + local x, y = sizes.xFinder + 1, sizes.yMain + --Фаворитсы + if #config.favourites > 0 then + buffer.text(x, y, colors.leftBarHeader, lang.favourites); y = y + 1 + for i = 1, #config.favourites do + drawAndHiglightPath(y, config.favourites[i]) + y = y + 1 + end + y = y + 1 + end + --Диски + buffer.text(x, y, colors.leftBarHeader, lang.disks); y = y + 1 + for i = 1, #disks do + drawAndHiglightPath(y, disks[i]) + end + + buffer.resetDrawLimit() +end + +local function drawMain() + buffer.square(sizes.xMain, sizes.yMain, sizes.mainWidth, sizes.mainHeight, colors.main) + + --Ебашим раб стол + buffer.setDrawLimit(sizes.xMain, sizes.yMain, sizes.mainWidth, sizes.mainHeight) + local differenceByPixels = sizes.yFileListStartPoint - sizes.yFileList + local differenceByIcons = math.floor(differenceByPixels / sizes.iconTotalHeight) + sizes.fromIcon = differenceByIcons < 2 and 1 or math.floor((differenceByIcons - 1) * sizes.xCountOfIcons) + 1 + local finalY = differenceByIcons < 2 and sizes.yFileList or sizes.yFileList + math.floor((differenceByIcons - 1) * sizes.iconTotalHeight) + local finalTotalCountOfIcons = sizes.totalCountOfIcons + 2 * sizes.xCountOfIcons + obj.DesktopIcons = MineOSCore.drawIconField(sizes.xMain + 2, finalY, sizes.xCountOfIcons, sizes.yCountOfIcons, sizes.fromIcon, finalTotalCountOfIcons, sizes.xSpaceBetweenIcons, sizes.ySpaceBetweenIcons, workPathHistory[currentWorkPathHistoryElement], fileList, config.showFileFormat, 0x262626) + buffer.resetDrawLimit() + + --Ебашим скроллбар + buffer.scrollBar(sizes.xFinderEnd, sizes.yMain, 1, sizes.mainHeight, #fileList, sizes.fromIcon, 0xCCCCCC, 0x666666) end --Рисуем нижнюю полосочку с путем local function drawBottomBar() --Подложка - buffer.square(xMain, yEnd, widthOfBottom, 1, colors.leftBar, 0xffffff, " ") + buffer.square(sizes.xMain, sizes.yFinderEnd, sizes.mainWidth + 1, 1, colors.leftBar, 0xffffff, " ") --Создаем переменную строки истории local historyString = workPathHistory[currentWorkPathHistoryElement] if historyString == "" or historyString == "/" then @@ -253,454 +249,126 @@ local function drawBottomBar() end end --Рисуем ее - buffer.text(xMain + 1, yEnd, colors.topText, ecs.stringLimit("start", historyString, widthOfMain - 2)) + buffer.text(sizes.xMain + 1, sizes.yFinderEnd, colors.topText, ecs.stringLimit("start", historyString, sizes.mainWidth - 2)) end ---Рисуем зону иконок -local function drawMain(fromLine) - --С какой линии начинать отрисовку - fromLine = fromLine or 1 - --Очищаем объекты - obj["Icons"] = {} - --Рисуем белую подложку - buffer.square(xMain, yLeftBar, widthOfMain, heightOfMain, colors.main, 0xffffff, " ") - --Рисуем скроллбарчик, епты бля! - local scrollHeight = math.ceil(#fileList / xCountOfIcons); if scrollHeight == 0 then scrollHeight = 1 end - buffer.scrollBar(xEnd, yLeftBar, 1, heightOfMain, scrollHeight, fromLine, colors.topBar, 0x555555) - --Позиции отрисовки иконок - local xPos, yPos = xMain + 1, yLeftBar + 1 - --С какой иконки начинать отрисовку - local counter = fromLine * xCountOfIcons - xCountOfIcons + 1 - --Перебираем квадрат иконочной зоны - for j = 1, yCountOfIcons do - for i = 1, xCountOfIcons do - --Разрываем цикл, если конец файл листа - if not fileList[counter] then break end - --Получаем путь к файлу для иконки - local path = workPathHistory[currentWorkPathHistoryElement] .. fileList[counter] - --Рисуем иконку - ecs.drawOSIcon(xPos, yPos, path, showFileFormat, 0x000000) - --Создаем объект иконки - newObj("Icons", counter, xPos, yPos, xPos + widthOfIcon - 1, yPos + heightOfIcon - 1, path) - --Очищаем оперативку - path = nil - --Увеличиваем xPos для след. иконки справа и cчетчик файлов - xPos = xPos + widthOfIcon + xSpaceBetweenIcons - counter = counter + 1 - end - --Сбрасываем xPos на старт и увеличиваем yPos для иконок ниже - xPos = xMain + 1 - yPos = yPos + heightOfIcon + ySpaceBetweenIcons - end -end - ---Рисуем левую часть -local function drawLeftBar() - obj["Favorites"] = {} - --Рисуем подложку лефтбара - buffer.square(x, yLeftBar, widthOfLeftBar, heightOfLeftBar, 0xffffff, 0xffffff, " ", 30) - buffer.scrollBar(x + widthOfLeftBar - 1, yLeftBar, 1, heightOfLeftBar, #leftBar, fromLineLeftBar, colors.topBar, 0x555555) - --Коорды - local xPos, yPos, limit = x + 1, yLeftBar, widthOfLeftBar - 3 - - --Перебираем массив лефтбара - for i = fromLineLeftBar, (heightOfLeftBar + fromLineLeftBar - 1) do - --Если в лефтбаре такой вообще существует вещ - if leftBar[i] then - --Рисуем заголовок - if leftBar[i][1] == "Title" then - buffer.text(xPos, yPos, colors.leftBarHeader, leftBar[i][2]) - else - --Делаем сразу строку - local text = ecs.stringLimit("end", leftBar[i][2], limit) - --Если текущий путь сопадает с путем фаворитса - if leftBar[i][3] == workPathHistory[currentWorkPathHistoryElement] then - buffer.square(x, yPos, widthOfLeftBar - 1, 1, colors.leftBarSelection, 0xffffff, " ") - buffer.text(xPos + 1, yPos, 0xffffff, text) - else - buffer.text(xPos + 1, yPos, colors.leftBarList,text ) - end - - newObj("Favorites", i, x, yPos, x + widthOfLeftBar - 1, yPos, leftBar[i][3]) - - end - - yPos = yPos + 1 - end - end -end - -local function drawShadows() - buffer.square(xEnd + 1, y + 1, 2, height, 0x000000, 0xffffff, " ", 60) - buffer.square(x + 2, yEnd + 1, width - 2, 1, 0x000000, 0xffffff, " ", 60) -end - ---Рисуем вообще все local function drawAll(force) - if isFullScreen then - buffer.paste(1, 1, oldPixelsOfFullScreen) - else - buffer.setDrawLimit(x, y, width + 2, height + 1) - buffer.paste(1, 1, oldPixelsOfFullScreen) - buffer.resetDrawLimit() - end drawTopBar() - drawBottomBar() drawLeftBar() - drawMain(fromLine) - drawShadows() + drawBottomBar() + drawMain() buffer.draw(force) end ---Назад по истории -local function backToPast() - if currentWorkPathHistoryElement > 1 then - --Го! - currentWorkPathHistoryElement = currentWorkPathHistoryElement - 1 - --Получаем список файлов текущей директории - getFileList(workPathHistory[currentWorkPathHistoryElement]) - --Раб стол перерисовываем, блеа! - fromLine = 1 - end - --Кнопы перерисовываем, ды! +local function getListAndDrawAll() + -- ecs.error("ДА ЕБАНА") + getFileList() drawAll() end ---Вперед по истории -local function backToFuture() - if currentWorkPathHistoryElement < #workPathHistory then - --Го! - currentWorkPathHistoryElement = currentWorkPathHistoryElement + 1 - --Получаем список файлов текущей директории - getFileList(workPathHistory[currentWorkPathHistoryElement]) - --Раб стол перерисовываем, блеа! - fromLine = 1 - end - --Кнопы перерисовываем, ды! - drawAll() -end - ---Добавить что-то в избранное -local function addToFavourites(name, path) - table.insert(leftBar, 2, {"Element", name, path}) +local function fullRefresh() + getFileList() + buffer.paste(1, 1, oldPixelsOfFullScreen) + drawAll(true) end ---------------------------------------------------------------------------------------------------------------------------------- -local args = { ... } --- local cykaImage = image.load("MineOS/Pictures/AhsokaTano.pic") --- buffer.image(1, 1, cykaImage) +local args = {...} +-- buffer.start() +-- buffer.clear(0xFF6666) ---Загружаем конфигурационный файл -loadConfig() ---Создаем дисковую парашу там вон -chkdsk() ---Задаем стартовые размеры -local startWidth, startHeight = 86, 25 -width = startWidth -height = startHeight ---Задаем стартовый путь -changePath(args[1] or "") ---Даем возможность авторасчета координат -local xStart, yStart = ecs.correctStartCoords("auto", "auto", width, height) -x, y = xStart, yStart ---Пересчитываем все размеры -calculateSizes() ---Запоминаем старые пиксели, чтобы потом можно было отрисовать предыдущий интерфейс --- oldPixelsOfMini = buffer.copy(x, y, width + 2, height + 1) oldPixelsOfFullScreen = buffer.copy(1, 1, buffer.screen.width, buffer.screen.height) -isFullScreen = false - ---Рисуем вообще все +MineOSCore.setLocalization(lang) +MineOSCore.loadIcons() +calculateSizes() +loadConfig() +createDisks() +changePath(args[1] == "open" and (args[2] or "") or "") drawAll() -local clickedOnEmptySpace while true do - local e = {event.pull()} - if e[1] == "touch" then - --Переменная, становящаяся ложью только в случае клика на какой-либо элемент, не суть какой - clickedOnEmptySpace = true - - --Перебираем иконки - for key in pairs(obj["Icons"]) do - if ecs.clickedAtArea(e[3], e[4], obj["Icons"][key][1], obj["Icons"][key][2], obj["Icons"][key][3], obj["Icons"][key][4]) then - --Рисуем иконку выделенную - buffer.square(obj["Icons"][key][1], obj["Icons"][key][2], widthOfIcon, heightOfIcon, colors.selection, 0xffffff, " ") - ecs.drawOSIcon(obj["Icons"][key][1], obj["Icons"][key][2], obj["Icons"][key][5], showFileFormat, 0xffffff) - buffer.draw() + local eventData = {event.pull()} + if eventData[1] == "touch" then + local clickedAtEmptyArea = true - --Получаем путь иконки и ее формат - local path = obj["Icons"][key][5] - local fileFormat = ecs.getFileFormat(path) - local action - - --Левая кнопка мыши - if e[5] == 0 then - os.sleep(0.2) - --Думаем, че делать дальше - if fs.isDirectory(path) and fileFormat ~= ".app" then - changePath(path) - drawAll() - else - ecs.launchIcon(path) - buffer.paste(1, 1, oldPixelsOfFullScreen) - drawAll(true) - end - --А если правая - else - if fs.isDirectory(path) then - if fileFormat ~= ".app" then - action = context.menu(e[3], e[4], {lang.contextMenuAddToFavourites},"-", {lang.contextMenuCopy, false, "^C"}, {lang.contextMenuRename}, {lang.contextMenuCreateShortcut}, "-", {lang.contextMenuArchive}, "-", {lang.contextMenuDelete, false, "⌫"}) - else - action = context.menu(e[3], e[4], {lang.contextMenuShowPackageContent}, {lang.contextMenuAddToFavourites},"-", {lang.contextMenuCopy, false, "^C"}, {lang.contextMenuRename}, {lang.contextMenuCreateShortcut}, "-", {lang.contextMenuArchive}, "-", {lang.contextMenuDelete, false, "⌫"}) - end - else - if fileFormat == ".pic" then - action = context.menu(e[3], e[4], {lang.contextMenuEdit}, {lang.contextMenuEditInPhotoshop}, {lang.contextMenuSetAsWallpaper}, "-", {lang.contextMenuCopy, false, "^C"}, {lang.contextMenuRename}, {lang.contextMenuCreateShortcut}, "-", {lang.contextMenuUploadToPastebin}, "-", {lang.contextMenuDelete, false, "⌫"}) - elseif fileFormat == ".lua" then - action = context.menu(e[3], e[4], {lang.contextMenuEdit}, {lang.contextMenuCreateApplication}, "-", {lang.contextMenuCopy, false, "^C"}, {lang.contextMenuRename}, {lang.contextMenuCreateShortcut}, "-", {lang.contextMenuUploadToPastebin}, "-", {lang.contextMenuDelete, false, "⌫"}) - else - action = context.menu(e[3], e[4], {lang.contextMenuEdit}, "-", {lang.contextMenuCopy, false, "^C"}, {lang.contextMenuRename}, {lang.contextMenuCreateShortcut}, "-", {lang.contextMenuUploadToPastebin}, "-", {lang.contextMenuDelete, false, "⌫"}) - end - end - - --АналИз действия - if action == lang.contextMenuEdit then - ecs.prepareToExit() - shell.execute("edit "..path) - buffer.paste(1, 1, oldPixelsOfFullScreen) - drawAll(true) - elseif action == lang.contextMenuEditInPhotoshop then - shell.execute("MineOS/Applications/Photoshop.app/Photoshop.lua open " .. path) - buffer.paste(1, 1, oldPixelsOfFullScreen) - drawAll(true) - elseif action == lang.contextMenuAddToFavourites then - addToFavourites(fs.name(path), path) - drawAll() - elseif action == lang.contextMenuShowPackageContent then - changePath(path) - drawAll() - elseif action == lang.contextMenuCopy then - _G.clipboard = path - drawAll() - elseif action == lang.contextMenuPaste then - ecs.copy(_G.clipboard, fs.path(path) or "") - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuDelete then - fs.remove(path) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuRename then - ecs.rename(path) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuCreateShortcut then - ecs.createShortCut(fs.path(path).."/"..ecs.hideFileFormat(fs.name(path))..".lnk", path) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuArchive then - ecs.info("auto", "auto", "", "Архивация файлов...") - archive.pack(ecs.hideFileFormat(fs.name(path))..".pkg", path) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuUploadToPastebin then - shell.execute("MineOS/Applications/Pastebin.app/Pastebin.lua upload " .. path) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll(true) - elseif action == lang.contextMenuSetAsWallpaper then - --ecs.error(path) - ecs.createShortCut("MineOS/System/OS/Wallpaper.lnk", path) - computer.pushSignal("OSWallpaperChanged") - -- buffer.paste(1, 1, oldPixelsOfFullScreen) - -- buffer.draw() - return - elseif action == lang.contextMenuCreateApplication then - ecs.newApplicationFromLuaFile(path, workPathHistory[currentWorkPathHistoryElement]) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - else - --Рисуем иконку выделенную - buffer.square(obj["Icons"][key][1], obj["Icons"][key][2], widthOfIcon, heightOfIcon, colors.main, 0xffffff, " ") - ecs.drawOSIcon(obj["Icons"][key][1], obj["Icons"][key][2], obj["Icons"][key][5], showFileFormat, 0x000000) - buffer.draw() - end - end - - - --Кликнули не в жопу! - clickedOnEmptySpace = false - break - end - end - - --ВНИМАНИЕ: ЖОПА!!!! - --КЛИКНУЛИ В ЖОПУ!!!!!! - if ecs.clickedAtArea(e[3], e[4], xMain, yLeftBar, xEnd, yEnd - 1) and clickedOnEmptySpace and e[5] == 1 then - action = context.menu(e[3], e[4], {lang.contextMenuNewFile}, {lang.contextMenuNewFolder}, {lang.contextMenuNewApplication}, "-", {lang.contextMenuPaste, (_G.clipboard == nil), "^V"}) - if action == lang.contextMenuNewFile then - ecs.newFile(workPathHistory[currentWorkPathHistoryElement]) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - --buffer.paste(1, 1, oldPixelsOfFullScreen) - drawAll(true) - elseif action == lang.contextMenuNewFolder then - ecs.newFolder(workPathHistory[currentWorkPathHistoryElement]) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuPaste then - ecs.copy(_G.clipboard, workPathHistory[currentWorkPathHistoryElement]) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - elseif action == lang.contextMenuNewApplication then - ecs.newApplication(workPathHistory[currentWorkPathHistoryElement]) - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - end - end - - --Перебираем всякую шнягу наверху - for key in pairs(obj["TopButtons"]) do - if ecs.clickedAtArea(e[3], e[4], obj["TopButtons"][key][1], obj["TopButtons"][key][2], obj["TopButtons"][key][3], obj["TopButtons"][key][4]) then - buffer.button(obj["TopButtons"][key][1], obj["TopButtons"][key][2], 3, 1, colors.topButtonsText, colors.topButtons, key) - buffer.draw() - os.sleep(0.2) - if key == ">" then - backToFuture() - elseif key == "<" then - backToPast() - end - - break - end - end - - --Фаворитсы слева - for key in pairs(obj["Favorites"]) do - if ecs.clickedAtArea(e[3], e[4], obj["Favorites"][key][1], obj["Favorites"][key][2], obj["Favorites"][key][3], obj["Favorites"][key][4]) then - - changePath(obj["Favorites"][key][5]) - drawAll() - - --Левая кнопка мыши - if e[5] == 1 then - local action = context.menu(e[3], e[4], {lang.contextMenuShowContainingFolder}, "-",{lang.contextMenuRemoveFromFavourites}) - if action == lang.contextMenuRemoveFromFavourites then - table.remove(leftBar, key) - drawAll() - elseif action == lang.contextMenuShowContainingFolder then - changePath(fs.path(leftBar[key][3]) or "") - drawAll() - end - end - - break - end - end - - --Кнопочки красивые наверху слева круглые кароч вот хыыы - for key in pairs(obj["Closes"]) do - if ecs.clickedAtArea(e[3], e[4], obj["Closes"][key][1], obj["Closes"][key][2], obj["Closes"][key][3], obj["Closes"][key][4]) then - - --Закрыть прогу - if key == 1 then - ecs.colorTextWithBack(obj["Closes"][key][1], obj["Closes"][key][2], ecs.colors.blue, colors.topBar, "⮾") - + if clickedAtEmptyArea then + if obj.search:isClicked(eventData[3], eventData[4]) then + searchBarText = "" + searchBarText = drawSearchBar(false) + if searchBarText == "" then searchBarText = nil end + sizes.yFileList = sizes.yFileListStartPoint + getListAndDrawAll() + clickedAtEmptyArea = false + elseif obj.close:isClicked(eventData[3], eventData[4]) then + obj.close:press(0.2) + clickedAtEmptyArea = false + return + elseif obj.showFormat:isClicked(eventData[3], eventData[4]) then + config.showFileFormat = not config.showFileFormat + saveConfig() + getListAndDrawAll() + clickedAtEmptyArea = false + elseif obj.showHidden:isClicked(eventData[3], eventData[4]) then + config.showHiddenFiles = not config.showHiddenFiles + saveConfig() + getListAndDrawAll() + clickedAtEmptyArea = false + elseif obj.sortingMethod:isClicked(eventData[3], eventData[4]) then + obj.sortingMethod:press(0.2) + local data = ecs.universalWindow("auto", "auto", 36, 0x262626, true, + {"EmptyLine"}, + {"CenterText", ecs.colors.orange, lang.sortingMethod}, + {"EmptyLine"}, + {"Selector", 0xFFFFFF, ecs.colors.orange, lang.sortByTypeShort, lang.sortByNameShort, lang.sortByDateShort}, + {"EmptyLine"}, + {"Button", {ecs.colors.orange, 0xffffff, "OK"}, {0x999999, 0xffffff, lang.cancel}} + ) + if data[2] == "OK" then + config.currentSortingMethod = sortingMethods[data[1]] saveConfig() - - return - - --Пока ниче не делать - elseif key == 2 and isFullScreen then - ecs.colorTextWithBack(obj["Closes"][key][1], obj["Closes"][key][2], ecs.colors.blue, colors.topBar, "⮾") - os.sleep(0.2) - x, y, width, height = xStart, yStart, startWidth, startHeight - isFullScreen = false - --Пересчитываем все размеры - calculateSizes() - --Рисуем старые пиксельсы из фулл скрина - buffer.paste(1, 1, oldPixelsOfFullScreen) - --Рисуем окно заново - drawAll() - --Масштаб - elseif key == 3 and not isFullScreen then - ecs.colorTextWithBack(obj["Closes"][key][1], obj["Closes"][key][2], ecs.colors.blue, colors.topBar, "⮾") - os.sleep(0.2) - --Задаем новые координаты окна - x = 1 - y = 1 - width, height = gpu.getResolution() - isFullScreen = true - --Пересчитываем все размеры - calculateSizes() - --Рисуем окно заново - drawAll() + getListAndDrawAll() end - - break end end - for key in pairs(obj["FSButtons"]) do - if ecs.clickedAtArea(e[3], e[4], obj["FSButtons"][key][1], obj["FSButtons"][key][2], obj["FSButtons"][key][3], obj["FSButtons"][key][4]) then - if key == 1 then - currentSortingMethod = 1 - elseif key == 2 then - currentSortingMethod = 2 - elseif key == 3 then - currentSortingMethod = 3 - elseif key == 4 then - showFileFormat = not showFileFormat - elseif key == 5 then - showHiddenFiles = not showHiddenFiles + if clickedAtEmptyArea then + for _, item in pairs(obj.leftBarItems) do + if item:isClicked(eventData[3], eventData[4]) then + changePath(item.path) + drawAll() + clickedAtEmptyArea = false + break end - fromLine = 1 - getFileList(workPathHistory[currentWorkPathHistoryElement]) - drawAll() - - break end end - elseif e[1] == "component_added" and e[3] == "filesystem" then - chkdsk() - drawAll() - elseif e[1] == "component_removed" and e[3] == "filesystem" then - chkdsk() - changePath("") - drawAll() - --Ретранслируем сигнал в ОС - elseif e[1] == "OSWallpaperChanged" then - computer.pushSignal("OSWallpaperChanged") - return - - elseif e[1] == "scroll" then - --Если скроллим в зоне иконок - if ecs.clickedAtArea(e[3], e[4], xMain, yLeftBar, xEnd, yEnd - 1) then - if e[5] == 1 then - if fromLine > 1 then - fromLine = fromLine - 1 - drawMain(fromLine) - buffer.draw() - end - else - if fromLine < (math.ceil(#fileList / xCountOfIcons)) then - fromLine = fromLine + 1 - drawMain(fromLine) - buffer.draw() + if clickedAtEmptyArea then + for _, icon in pairs(obj.DesktopIcons) do + if icon:isClicked(eventData[3], eventData[4]) then + buffer.setDrawLimit(sizes.xMain, sizes.yMain, sizes.mainWidth, sizes.mainHeight) + if MineOSCore.iconClick(icon, eventData, colors.selection, nil, 0xFFFFFF, 0.2, config.showFileFormat, {method = getListAndDrawAll, arguments = {}}, {method = fullRefresh, arguments = {}}, {method = changePath, arguments = {icon.path}}) then return end + buffer.resetDrawLimit() + clickedAtEmptyArea = false + break end end + end - --А если в зоне лефтбара - elseif ecs.clickedAtArea(e[3], e[4], x, yLeftBar, x + widthOfLeftBar - 1, yEnd) then - if e[5] == 1 then - if fromLineLeftBar > 1 then - fromLineLeftBar = fromLineLeftBar - 1 - drawAll() + if clickedAtEmptyArea and obj.mainZone:isClicked(eventData[3], eventData[4]) then + MineOSCore.emptyZoneClick(eventData, workPathHistory[currentWorkPathHistoryElement], {method = getListAndDrawAll, arguments = {}}) + end + elseif eventData[1] == "scroll" then + if obj.mainZone:isClicked(eventData[3], eventData[4]) then + if eventData[5] == 1 then + if sizes.yFileList < sizes.yFileListStartPoint then + sizes.yFileList = sizes.yFileList + scrollSpeed + drawMain(); buffer.draw() end else - if fromLineLeftBar < #leftBar then - fromLineLeftBar = fromLineLeftBar + 1 - drawAll() + if sizes.fromIcon < #fileList - sizes.xCountOfIcons then + sizes.yFileList = sizes.yFileList - scrollSpeed + drawMain(); buffer.draw() end end end @@ -708,3 +376,8 @@ while true do end + + + + + diff --git a/Applications/VK/IMG_3226.jpg b/Applications/VK/IMG_3226.jpg new file mode 100644 index 00000000..8137457c Binary files /dev/null and b/Applications/VK/IMG_3226.jpg differ diff --git a/Applications/VK/IMG_3229.jpg b/Applications/VK/IMG_3229.jpg new file mode 100644 index 00000000..51a59c14 Binary files /dev/null and b/Applications/VK/IMG_3229.jpg differ diff --git a/MineOS/Languages/English.lang b/MineOS/Languages/English.lang index 65d15162..047bee2b 100644 --- a/MineOS/Languages/English.lang +++ b/MineOS/Languages/English.lang @@ -22,6 +22,10 @@ contextMenuShowContainingFolder = "Show containing folder", contextMenuRemoveFromFavourites = "Remove from favourites", + favourites = "Favourites", + disks = "HDDs", + network = "Network", + search = "Search", sortByType = "Sort by type", sortByName = "Sort by name", sortByDate = "Sort by date", @@ -35,6 +39,7 @@ sortByDateShort = "By date", showFileFormatShort = "Format", showHiddenFilesShort = "Hidden", + sortingMethod = "Sorting method", aboutSystem = "About this PC", updates = "Updates", @@ -71,7 +76,8 @@ screenResolution = "Screen resolution", settings = "Preferences", changePassword = "Change password", - cancel = "Отмена", + cancel = "Cancel", + shortcutIsCorrupted = "Shortcut file is corrupted", viewTab = "View", } \ No newline at end of file diff --git a/MineOS/Languages/Russian.lang b/MineOS/Languages/Russian.lang index 6862c32b..839d3a38 100644 --- a/MineOS/Languages/Russian.lang +++ b/MineOS/Languages/Russian.lang @@ -11,7 +11,7 @@ contextMenuRename = "Переименовать", contextMenuCreateShortcut = "Создать ярлык", contextMenuUploadToPastebin = "Загрузить на Pastebin", - contextMenuAddToDock = "Добавит в Dock", + contextMenuAddToDock = "Добавить в Dock", contextMenuRemoveFromDock = "Удалить из Dock", contextMenuArchive = "Добавить в архив", contextMenuDelete = "Удалить", @@ -22,6 +22,10 @@ contextMenuShowContainingFolder = "Показать содержащую папку", contextMenuRemoveFromFavourites = "Удалить из избранного", + favourites = "Избранное", + disks = "Диски", + network = "Сеть", + search = "Поиск", sortByType = "Сортировать по типу", sortByName = "Сортировать по имени", sortByDate = "Сортировать по дате", @@ -35,6 +39,7 @@ sortByDateShort = "По дате", showFileFormatShort = "Формат", showHiddenFilesShort = "Скрытые", + sortingMethod = "Упорядочить", aboutSystem = "Об этом ПК", updates = "Обновления", @@ -72,6 +77,7 @@ settings = "Настройки", changePassword = "Изменить пароль", cancel = "Отмена", + shortcutIsCorrupted = "Файл ярлыка поврежден или имеет неизвестный формат", viewTab = "Вид", } \ No newline at end of file diff --git a/MineOS/OS.lua b/MineOS/OS.lua index 59f7f7e7..11f36817 100644 --- a/MineOS/OS.lua +++ b/MineOS/OS.lua @@ -1,3 +1,5 @@ +-- package.loaded.MineOSCore = nil +-- _G.MineOSCore = nil ---------------------------------------------- Копирайт, епта ------------------------------------------------------------------------ @@ -22,14 +24,15 @@ local copyright = [[ -- Адаптивная загрузка необходимых библиотек и компонентов local libraries = { + MineOSCore = "MineOSCore", + buffer = "doubleBuffering", + image = "image", ecs = "ECSAPI", component = "component", event = "event", term = "term", files = "files", context = "context", - buffer = "doubleBuffering", - image = "image", SHA2 = "SHA2", GUI = "GUI" } @@ -50,7 +53,6 @@ local lang = files.loadTableFromFile("MineOS/System/OS/Languages/" .. _G.OSSetti local workPath = "MineOS/Desktop/" local pathOfDockShortcuts = "MineOS/System/OS/Dock/" local pathToWallpaper = "MineOS/System/OS/Wallpaper.lnk" -local currentFileList local currentDesktop = 1 local showHiddenFiles = false local showFileFormat = false @@ -84,9 +86,7 @@ local sizes = { --Рерасчет всех необходимых параметров local function calculateSizes() - sizes.xCountOfIcons = math.floor(buffer.screen.width / (sizes.widthOfIcon + sizes.xSpaceBetweenIcons)) - sizes.yCountOfIcons = math.floor((buffer.screen.height - (sizes.heightOfDock + 7)) / (sizes.heightOfIcon + sizes.ySpaceBetweenIcons)) - sizes.desktopCountOfIcons = sizes.xCountOfIcons * sizes.yCountOfIcons + sizes.xCountOfIcons, sizes.yCountOfIcons, sizes.totalCountOfIcons = MineOSCore.getParametersForDrawingIcons(buffer.screen.width, buffer.screen.height - sizes.heightOfDock - 6, sizes.xSpaceBetweenIcons, sizes.ySpaceBetweenIcons) sizes.yPosOfIcons = 3 sizes.xPosOfIcons = math.floor(buffer.screen.width / 2 - (sizes.xCountOfIcons * (sizes.widthOfIcon + sizes.xSpaceBetweenIcons) - sizes.xSpaceBetweenIcons) / 2) sizes.dockCountOfIcons = sizes.xCountOfIcons - 1 @@ -114,36 +114,14 @@ end --ОТРИСОВКА ИКОНОК НА РАБОЧЕМ СТОЛЕ ПО ТЕКУЩЕЙ ПАПКЕ local function drawDesktop() - obj.DesktopIcons = {} obj.DesktopCounters = {} - currentFileList = ecs.getFileList(workPath) - currentFileList = ecs.sortFiles(workPath, currentFileList, sortingMethod, showHiddenFiles) + local fileList = ecs.getFileList(workPath) + fileList = ecs.sortFiles(workPath, fileList, sortingMethod, showHiddenFiles) - --Получаем количество рабочих столов - sizes.countOfDesktops = math.ceil(#currentFileList / sizes.desktopCountOfIcons) - - local fileToDrawFrom = currentDesktop * sizes.desktopCountOfIcons - sizes.desktopCountOfIcons + 1 - - --Отрисовка иконок по файл-листу - local counter = 1 - local xPos, yPos = sizes.xPosOfIcons, sizes.yPosOfIcons - for i = fileToDrawFrom, (fileToDrawFrom + sizes.desktopCountOfIcons - 1) do - if not currentFileList[i] then break end - --Отрисовка конкретной иконки - local path = workPath .. currentFileList[i] - ecs.drawOSIcon(xPos, yPos, path, showFileFormat, 0xffffff) - --Создание объекта иконки - obj.DesktopIcons[i] = GUI.object(xPos, yPos, sizes.widthOfIcon, sizes.heightOfIcon) - obj.DesktopIcons[i].path = path - - xPos = xPos + sizes.widthOfIcon + sizes.xSpaceBetweenIcons - counter = counter + 1 - if counter > sizes.xCountOfIcons then - xPos = sizes.xPosOfIcons - yPos = yPos + sizes.heightOfIcon + sizes.ySpaceBetweenIcons - counter = 1 - end - end + --Ебашим раб стол + sizes.countOfDesktops = math.ceil(#fileList / sizes.totalCountOfIcons) + local fromIcon = currentDesktop * sizes.totalCountOfIcons - sizes.totalCountOfIcons + 1 + obj.DesktopIcons = MineOSCore.drawIconField(sizes.xPosOfIcons, sizes.yPosOfIcons, sizes.xCountOfIcons, sizes.yCountOfIcons, fromIcon, sizes.totalCountOfIcons, sizes.xSpaceBetweenIcons, sizes.ySpaceBetweenIcons, workPath, fileList, showFileFormat, 0xFFFFFF) --Отрисовываем пиздюлинки под раб столы local width = 4 * sizes.countOfDesktops - 2 @@ -187,7 +165,7 @@ local function drawDock() local yIcons = buffer.screen.height - sizes.heightOfDock - 1 for i = 1, currentCountOfIconsInDock do - ecs.drawOSIcon(xIcons, yIcons, pathOfDockShortcuts .. dockShortcuts[i], showFileFormat, 0x000000) + MineOSCore.drawIcon(xIcons, yIcons, pathOfDockShortcuts .. dockShortcuts[i], showFileFormat, 0x000000) obj.DockIcons[i] = GUI.object(xIcons, yIcons, sizes.widthOfIcon, sizes.heightOfIcon) obj.DockIcons[i].path = dockShortcuts[i] xIcons = xIcons + sizes.xSpaceBetweenIcons + sizes.widthOfIcon @@ -429,6 +407,8 @@ end ---------------------------------------------- Сама ОС ------------------------------------------------------------------------ ecs.loadOSSettings() +MineOSCore.setLocalization(lang) +MineOSCore.loadIcons() changeResolution() changeWallpaper() drawAll(true) @@ -446,158 +426,27 @@ while true do for _, icon in pairs(obj.DesktopIcons) do if icon:isClicked(eventData[3], eventData[4]) then - local fileFormat = ecs.getFileFormat(icon.path) - - local oldPixelsOfIcon = buffer.copy(icon.x, icon.y, sizes.widthOfIcon, sizes.heightOfIcon) - - buffer.square(icon.x, icon.y, sizes.widthOfIcon, sizes.heightOfIcon, colors.selection, 0xFFFFFF, " ", colors.iconsSelectionTransparency) - ecs.drawOSIcon(icon.x, icon.y, icon.path, false, 0xffffff) - buffer.draw() - - -- Левый клик - if eventData[5] == 0 then - os.sleep(0.2) - if fs.isDirectory(icon.path) then - if fileFormat == ".app" then - ecs.launchIcon(icon.path) - buffer.start() - drawAll() - else - shell.execute("MineOS/Applications/Finder.app/Finder.lua " .. icon.path) - drawAll() - end - else - ecs.launchIcon(icon.path) - buffer.start() - drawAll() - end - - -- Правый клик - elseif eventData[5] == 1 then - - local action - local fileFormat = ecs.getFileFormat(icon.path) - - -- Разные контекстные меню - if fs.isDirectory(icon.path) then - if fileFormat == ".app" then - action = context.menu(eventData[3], eventData[4], - {lang.contextMenuShowPackageContent}, - "-", - {lang.contextMenuCopy, false}, - {lang.contextMenuPaste, not _G.clipboard}, - "-", - {lang.contextMenuRename}, - {lang.contextMenuCreateShortcut}, - "-", - {lang.contextMenuUploadToPastebin, true}, - "-", - {lang.contextMenuAddToDock, not (currentCountOfIconsInDock < sizes.dockCountOfIcons)}, - {lang.contextMenuDelete, false} - ) - else - action = context.menu(eventData[3], eventData[4], - {lang.contextMenuCopy, false}, - {lang.contextMenuRename}, - {lang.contextMenuCreateShortcut}, - "-", - {lang.contextMenuArchive}, - "-", - {lang.contextMenuDelete, false} - ) - end - else - if fileFormat == ".pic" then - action = context.menu(eventData[3], eventData[4], - {lang.contextMenuEdit}, - {lang.contextMenuEditInPhotoshop}, - {lang.contextMenuSetAsWallpaper}, - "-", - {lang.contextMenuCopy, false}, - {lang.contextMenuRename}, - {lang.contextMenuCreateShortcut}, - "-", - {lang.contextMenuUploadToPastebin, true}, - "-", - {lang.contextMenuAddToDock, not (currentCountOfIconsInDock < sizes.dockCountOfIcons)}, - {lang.contextMenuDelete, false} - ) - else - action = context.menu(eventData[3], eventData[4], - {lang.contextMenuEdit}, - -- {lang.contextMenuCreateApplication}, - "-", - {lang.contextMenuCopy, false}, - {lang.contextMenuRename}, - {lang.contextMenuCreateShortcut}, - "-", - {lang.contextMenuUploadToPastebin, true}, - "-", - {lang.contextMenuAddToDock, not (currentCountOfIconsInDock < sizes.dockCountOfIcons and workPath ~= "MineOS/System/OS/Dock/")}, - {lang.contextMenuDelete, false} - ) - end - end - - --Анализ действия контекстного меню - if action == lang.contextMenuShowPackageContent then - shell.execute("MineOS/Applications/Finder.app/Finder.lua ".. icon.path) - elseif action == lang.contextMenuEdit then - ecs.editFile(icon.path) - drawAll(true) - elseif action == lang.contextMenuDelete then - fs.remove(icon.path) - drawAll() - elseif action == lang.contextMenuCopy then - _G.clipboard = icon.path - elseif action == lang.contextMenuPaste then - ecs.copy(_G.clipboard, workPath) - drawAll() - elseif action == lang.contextMenuRename then - ecs.rename(icon.path) - drawAll() - elseif action == lang.contextMenuCreateShortcut then - ecs.createShortCut(workPath .. ecs.hideFileFormat(icon.path) .. ".lnk", icon.path) - drawAll() - elseif action == lang.contextMenuAddToDock then - ecs.createShortCut("MineOS/System/OS/Dock/" .. ecs.hideFileFormat(icon.path) .. ".lnk", icon.path) - drawAll() - elseif action == lang.contextMenuSetAsWallpaper then - ecs.createShortCut(pathToWallpaper, icon.path) - changeWallpaper() - drawAll(true) - elseif action == lang.contextMenuEditInPhotoshop then - shell.execute("MineOS/Applications/Photoshop.app/Photoshop.lua open " .. icon.path) - drawAll(true) - else - buffer.paste(icon.x, icon.y, oldPixelsOfIcon) - buffer.draw() - end - end - + if MineOSCore.iconClick(icon, eventData, colors.selection, colors.iconsSelectionTransparency, 0xFFFFFF, 0.2, showFileFormat, {method = drawAll, arguments = {}}, {method = drawAll, arguments = {}}, {method = function() MineOSCore.safeLaunch("Finder.lua", "open", icon.path) end, arguments = {icon.path}}) then return end clickedAtEmptyArea = false - break end end for _, icon in pairs(obj.DockIcons) do if icon:isClicked(eventData[3], eventData[4]) then - local oldPixelsOfIcon = buffer.copy(icon.x, icon.y, sizes.widthOfIcon, sizes.heightOfIcon) buffer.square(icon.x, icon.y, sizes.widthOfIcon, sizes.heightOfIcon, colors.selection, 0xFFFFFF, " ", colors.iconsSelectionTransparency) - ecs.drawOSIcon(icon.x, icon.y, pathOfDockShortcuts .. icon.path, false, 0xffffff) + MineOSCore.drawIcon(icon.x, icon.y, pathOfDockShortcuts .. icon.path, false, 0xffffff) buffer.draw() if eventData[5] == 0 then os.sleep(0.2) - ecs.launchIcon(pathOfDockShortcuts .. icon.path) + MineOSCore.launchIcon(pathOfDockShortcuts .. icon.path) drawAll(true) else local content = ecs.readShortcut(pathOfDockShortcuts .. icon.path) - - action = context.menu(eventData[3], eventData[4],{lang.contextMenuRemoveFromDock, not (currentCountOfIconsInDock > 1)}) + action = context.menu(eventData[3], eventData[4], {lang.contextMenuRemoveFromDock, not (currentCountOfIconsInDock > 1)}) if action == lang.contextMenuRemoveFromDock then fs.remove(pathOfDockShortcuts .. icon.path) @@ -610,7 +459,6 @@ while true do end clickedAtEmptyArea = false - break end end @@ -766,32 +614,7 @@ while true do end if clickedAtEmptyArea and eventData[5] == 1 then - local action = context.menu(eventData[3], eventData[4], - {lang.contextMenuRemoveWallpaper, not wallpaper}, - "-", - {lang.contextMenuNewFile}, - {lang.contextMenuNewFolder}, - "-", - {lang.contextMenuPaste, not _G.clipboard} - ) - - --Создать новый файл - if action == lang.contextMenuNewFile then - ecs.newFile(workPath) - drawAll(true) - --Создать новую папку - elseif action == lang.contextMenuNewFolder then - ecs.newFolder(workPath) - drawAll() - --Вставить файл - elseif action == lang.contextMenuPaste then - ecs.copy(_G.clipboard, workPath) - drawAll() - elseif action == lang.contextMenuRemoveWallpaper then - wallpaper = nil - fs.remove(pathToWallpaper) - drawAll() - end + MineOSCore.emptyZoneClick(eventData, workPath, {method = drawAll, arguments = {}}) end elseif eventData[1] == "OSWallpaperChanged" then changeWallpaper() diff --git a/lib/GUI.lua b/lib/GUI.lua index 43ff4122..db0444f3 100644 --- a/lib/GUI.lua +++ b/lib/GUI.lua @@ -1,7 +1,11 @@ -if not _G.buffer then _G.buffer = require("doubleBuffering") end -if not _G.ecs then _G.ecs = require("ECSAPI") end -if not _G.unicode then _G.unicode = require("unicode") end +local libraries = { + buffer = "doubleBuffering", + ecs = "ECSAPI", + unicode = "unicode" +} + +for library in pairs(libraries) do if not _G[library] then _G[library] = require(libraries[library]) end end; libraries = nil local GUI = {} ---------------------------------------------------- Универсальные методы -------------------------------------------------------- @@ -201,10 +205,11 @@ function GUI.error(text, errorWindowParameters) local widthOfText = math.floor(buffer.screen.width * 0.5) --Ебемся с текстом, делаем его пиздатым во всех смыслах - if type(text) == "table" then text = serialization.serialize(text) end - text = tostring(text) - text = (errorWindowParameters and errorWindowParameters.truncate) and ecs.stringLimit("end", text, errorWindowParameters.truncate) or text - text = { text } + if type(text) ~= "table" then + text = tostring(text) + text = (errorWindowParameters and errorWindowParameters.truncate) and ecs.stringLimit("end", text, errorWindowParameters.truncate) or text + text = { text } + end text = ecs.stringWrap(text, widthOfText) @@ -262,6 +267,121 @@ end -------------------------------------------------------------------------------------------------------------------------------- +-- local textFieldProperties = { +-- --Регурярное выражение, которому должны соответствовать вводимые данные. При несоответствии на выходе из функции выдается первоначальный текст, поданынй на выход функции +-- regex = "^%d+$", +-- --Отключает символ многоточия при выходе за пределы текстового поля +-- disableDots = true, +-- --Попросту отрисовывает всю необходимую информацию без активации нажатия на клавиши +-- justDrawNotEvent = true, +-- --Задержка между миганимем курсора +-- cursorBlinkDelay = 1.5, +-- --Цвет курсора +-- cursorColor = 0xFF7777, +-- --Символ, используемый для отрисовки курсора +-- cursorSymbol = "▌", +-- --Символ-маскировщик, на который будет визуально заменен весь вводимый текст. Полезно для полей ввода пароля +-- maskTextWithSymbol = "*", +-- } + +function GUI.input(x, y, width, foreground, startText, textFieldProperties) + local text = startText + local textLength = unicode.len(text) + local cursorBlinkState = false + local cursorBlinkDelay = (textFieldProperties and textFieldProperties.cursorBlinkDelay) and textFieldProperties.cursorBlinkDelay or 0.5 + local cursorColor = (textFieldProperties and textFieldProperties.cursorColor) and textFieldProperties.cursorColor or 0x00A8FF + local cursorSymbol = (textFieldProperties and textFieldProperties.cursorSymbol) and textFieldProperties.cursorSymbol or "┃" + + local oldPixels = {}; for i = x, x + width - 1 do table.insert(oldPixels, { buffer.get(i, y) }) end + + local function drawOldPixels() + for i = 1, #oldPixels do buffer.set(x + i - 1, y, oldPixels[i][1], oldPixels[i][2], oldPixels[i][3]) end + end + + local function getTextLength() + textLength = unicode.len(text) + end + + local function textFormat() + local formattedText = text + + if textFieldProperties and textFieldProperties.maskTextWithSymbol then + formattedText = string.rep(textFieldProperties.maskTextWithSymbol or "*", textLength) + end + + if textLength > width then + if textFieldProperties and textFieldProperties.disableDots then + formattedText = unicode.sub(formattedText, -width, -1) + else + formattedText = "…" .. unicode.sub(formattedText, -width + 1, -1) + end + end + + return formattedText + end + + local function draw() + drawOldPixels() + buffer.text(x, y, foreground, textFormat()) + + if cursorBlinkState then + local cursorPosition = textLength < width and x + textLength or x + width - 1 + local bg = buffer.get(cursorPosition, y) + buffer.set(cursorPosition, y, bg, cursorColor, cursorSymbol) + end + + buffer.draw() + end + + local function backspace() + if unicode.len(text) > 0 then text = unicode.sub(text, 1, -2); getTextLength(); draw() end + end + + local function quit() + cursorBlinkState = false + if textFieldProperties and textFieldProperties.regex and not string.match(text, textFieldProperties.regex) then + text = startText + draw() + return startText + end + draw() + return text + end + + draw() + + if textFieldProperties and textFieldProperties.justDrawNotEvent then return startText end + + while true do + local e = { event.pull(cursorBlinkDelay) } + if e[1] == "key_down" then + if e[4] == 14 then + backspace() + elseif e[4] == 28 then + return quit() + else + local symbol = unicode.char(e[3]) + if not keyboard.isControl(e[3]) then + text = text .. symbol + getTextLength() + draw() + end + end + elseif e[1] == "clipboard" then + text = text .. e[3] + getTextLength() + draw() + elseif e[1] == "touch" then + return quit() + else + cursorBlinkState = not cursorBlinkState + draw() + end + end +end + +-------------------------------------------------------------------------------------------------------------------------------- + -- buffer.clear(0xFFAAAA) -- buffer.draw(true) diff --git a/lib/MineOSCore.lua b/lib/MineOSCore.lua new file mode 100644 index 00000000..a7cf39a3 --- /dev/null +++ b/lib/MineOSCore.lua @@ -0,0 +1,423 @@ +---------------------------------------------- Библиотеки ------------------------------------------------------------------------ + +local libraries = { + computer = "computer", + ecs = "ECSAPI", + component = "component", + files = "files", + fs = "filesystem", + context = "context", + buffer = "doubleBuffering", + image = "image", + GUI = "GUI", + zip = "archive" +} + +for library in pairs(libraries) do if not _G[library] then _G[library] = require(libraries[library]) end end +libraries = nil + +-- Загрузка языкового пакета +-- local lang = files.loadTableFromFile("MineOS/System/OS/Languages/" .. _G.OSSettings.language .. ".lang") +local lang = {} +local MineOSCore = {} + +----------------------------------------------------------------------------------------------------------------------------------- + +MineOSCore.iconsPath = "MineOS/System/OS/Icons/" +MineOSCore.iconWidth = 12 +MineOSCore.iconHeight = 6 +MineOSCore.sortingMethods = { + type = 0, + name = 1, + date = 2, +} +MineOSCore.colors = { + background = 0x262626. +} + +----------------------------------------------------------------------------------------------------------------------------------- + +--Присвоение языкового пакета +function MineOSCore.setLocalization(langArray) + lang = langArray +end + +--Вся необходимая информация для иконок +function MineOSCore.loadIcons() + if MineOSCore.icons then return end + MineOSCore.icons = {} + MineOSCore.icons.folder = image.load(MineOSCore.iconsPath .. "Folder.pic") + MineOSCore.icons.script = image.load(MineOSCore.iconsPath .. "Script.pic") + MineOSCore.icons.text = image.load(MineOSCore.iconsPath .. "Text.pic") + MineOSCore.icons.config = image.load(MineOSCore.iconsPath .. "Config.pic") + MineOSCore.icons.lua = image.load(MineOSCore.iconsPath .. "Lua.pic") + MineOSCore.icons.image = image.load(MineOSCore.iconsPath .. "Image.pic") + MineOSCore.icons.pastebin = image.load(MineOSCore.iconsPath .. "Pastebin.pic") + MineOSCore.icons.fileNotExists = image.load(MineOSCore.iconsPath .. "FileNotExists.pic") + MineOSCore.icons.archive = image.load(MineOSCore.iconsPath .. "Archive.pic") + MineOSCore.icons.model3D = image.load(MineOSCore.iconsPath .. "3DModel.pic") +end + +--Отрисовка одной иконки +function MineOSCore.drawIcon(x, y, path, showFileFormat, nameColor) + local fileFormat, icon = ecs.getFileFormat(path) + + if fs.isDirectory(path) then + if fileFormat == ".app" then + -- icon = "cyka" + -- MineOSCore.icons[icon] = image.load(path .. "/Resources/Icon.pic") + icon = path .. "/Resources/Icon.pic" + if not MineOSCore.icons[icon] then + MineOSCore.icons[icon] = image.load(icon) + end + else + icon = "folder" + end + else + if fileFormat == ".lnk" then + MineOSCore.drawIcon(x, y, ecs.readShortcut(path), showFileFormat, nameColor) + buffer.set(x + MineOSCore.iconWidth - 3, y + MineOSCore.iconHeight - 3, 0xFFFFFF, 0x000000, "<") + return 0 + elseif fileFormat == ".cfg" or fileFormat == ".config" then + icon = "config" + elseif fileFormat == ".txt" or fileFormat == ".rtf" then + icon = "text" + elseif fileFormat == ".lua" then + icon = "lua" + elseif fileFormat == ".pic" or fileFormat == ".png" then + icon = "image" + elseif fileFormat == ".paste" then + icon = "pastebin" + elseif fileFormat == ".pkg" then + icon = "archive" + elseif fileFormat == ".3dm" then + icon = "model3D" + elseif not fs.exists(path) then + icon = "fileNotExists" + else + icon = "script" + end + end + + --Рисуем иконку + buffer.image(x + 2, y, MineOSCore.icons[icon]) + + --Делаем текст для иконки + local text = fs.name(path) + if not showFileFormat and fileFormat then text = unicode.sub(text, 1, -(unicode.len(fileFormat) + 1)) end + text = ecs.stringLimit("end", text, MineOSCore.iconWidth) + x = x + math.floor(MineOSCore.iconWidth / 2 - unicode.len(text) / 2) + --Рисуем текст под иконкой + buffer.text(x, y + MineOSCore.iconHeight - 1, nameColor or 0xffffff, text) +end + +function MineOSCore.safeLaunch(command, ...) + local success, reason = pcall(loadfile(command), ...) + --Ебал я автора мода в задницу, кусок ебанутого говна + --Какого хуя я должен вставлять кучу костылей в свой прекрасный код только потому, что эта ублюдочная + --скотина захотела выдавать table из pcall? Что, блядь? Где это видано, сука? + --Почему тогда во всех случаях выдается string, а при os.exit выдается {reason = "terminated"}? + --Что за ебливая сучья логика? + if not success and type(reason) ~= "table" then + reason = ecs.parseErrorMessage(reason, false) + GUI.error(reason, {title = {color = 0xFFDB40, text = "Ошибка при выполнении программы"}}) + end +end + +-- Запуск приложения +function MineOSCore.launchIcon(path, translate) + --Запоминаем, какое разрешение было + local oldWidth, oldHeight = component.gpu.getResolution() + --Получаем файл формат заранее + local fileFormat = ecs.getFileFormat(path) + local isDirectory = fs.isDirectory(path) + --Если это приложение + if fileFormat == ".app" then + ecs.applicationHelp(path) + MineOSCore.safeLaunch(path .. "/" .. ecs.hideFileFormat(fs.name(path)) .. ".lua") + --Если это папка + elseif (fileFormat == "" or fileFormat == nil) and isDirectory then + MineOSCore.safeLaunch("MineOS/Applications/Finder.app/Finder.lua " .. path) + --Если это обычный луа файл - т.е. скрипт + elseif fileFormat == ".lua" or fileFormat == nil then + buffer.clear(MineOSCore.colors.background) + ecs.prepareToExit() + MineOSCore.safeLaunch(path) + + --Если это фоточка + elseif fileFormat == ".pic" then + MineOSCore.safeLaunch("MineOS/Applications/Viewer.app/Viewer.lua", "open", path) + + --Если это 3D-модель + elseif fileFormat == ".3dm" then + MineOSCore.safeLaunch("MineOS/Applications/3DPrint.app/3DPrint.lua open " .. path) + + --Если это текст или конфиг или языковой + elseif fileFormat == ".txt" or fileFormat == ".cfg" or fileFormat == ".lang" then + ecs.prepareToExit() + MineOSCore.safeLaunch("bin/edit.lua", path) + + --Если это ярлык + elseif fileFormat == ".lnk" then + local shortcutLink = ecs.readShortcut(path) + if fs.exists(shortcutLink) then + MineOSCore.launchIcon(shortcutLink) + else + GUI.error(lang.shortcutIsCorrupted) + end + + --Если это архив + elseif fileFormat == ".zip" then + zip.unarchive(path, (fs.path(path) or "")) + end + --Ставим старое разрешение + component.gpu.setResolution(oldWidth, oldHeight) + buffer.start() +end + +----------------------------------------------------------------------------------------------------------------------------------- + +function MineOSCore.getParametersForDrawingIcons(fieldWidth, fieldHeight, xSpaceBetweenIcons, ySpaceBetweenIcons) + local xCountOfIcons, yCountOfIcons = math.floor(fieldWidth / (MineOSCore.iconWidth + xSpaceBetweenIcons)), math.floor(fieldHeight / (MineOSCore.iconHeight + ySpaceBetweenIcons)) + local totalCountOfIcons = xCountOfIcons * yCountOfIcons + return xCountOfIcons, yCountOfIcons, totalCountOfIcons +end + +function MineOSCore.drawIconField(x, y, xCountOfIcons, yCountOfIcons, fromIcon, totalCountOfIcons, xSpaceBetweenIcons, ySpaceBetweenIcons, path, fileList, showFileFormat, iconTextColor) + local iconObjects = {} + + local xPos, yPos, iconCounter = x, y, 1 + for i = fromIcon, (fromIcon + totalCountOfIcons - 1) do + if not fileList[i] then break end + + local iconObject = GUI.object(xPos, yPos, MineOSCore.iconWidth, MineOSCore.iconHeight) + iconObject.path = path .. fileList[i] + table.insert(iconObjects, iconObject) + MineOSCore.drawIcon(xPos, yPos, iconObject.path, showFileFormat, iconTextColor) + + xPos = xPos + MineOSCore.iconWidth + xSpaceBetweenIcons + iconCounter = iconCounter + 1 + if iconCounter > xCountOfIcons then + xPos = x + yPos = yPos + MineOSCore.iconHeight + ySpaceBetweenIcons + iconCounter = 1 + end + end + + return iconObjects +end + +----------------------------------------------------------------------------------------------------------------------------------- + +local function executeMethod(methodArray) + methodArray.method(table.unpack(methodArray.arguments)) +end + +function MineOSCore.iconSelect(icon, selectionColor, selectionTransparency, iconTextColor) + local oldPixelsOfIcon = buffer.copy(icon.x, icon.y, MineOSCore.iconWidth, MineOSCore.iconHeight) + buffer.square(icon.x, icon.y, MineOSCore.iconWidth, MineOSCore.iconHeight, selectionColor, 0xFFFFFF, " ", selectionTransparency) + MineOSCore.drawIcon(icon.x, icon.y, icon.path, false, iconTextColor) + buffer.draw() + return oldPixelsOfIcon +end + +function MineOSCore.iconLeftClick(icon, oldPixelsOfIcon, fileFormat, drawAllMethod, fullRefreshMethod, changeCurrentPathMethod) + if fs.isDirectory(icon.path) then + if fileFormat == ".app" then + MineOSCore.launchIcon(icon.path) + executeMethod(fullRefreshMethod) + else + executeMethod(changeCurrentPathMethod) + executeMethod(drawAllMethod) + end + else + MineOSCore.launchIcon(icon.path) + buffer.start() + executeMethod(fullRefreshMethod) + -- GUI.error("Скрипт выполнен успешно") + end +end + +function MineOSCore.iconRightClick(icon, oldPixelsOfIcon, eventData, fileFormat, somethingCanBeAddedToDock, drawAllMethod, fullRefreshMethod, changeCurrentPathMethod) + local action + -- Разные контекстные меню + if fs.isDirectory(icon.path) then + if fileFormat == ".app" then + action = context.menu(eventData[3], eventData[4], + {lang.contextMenuShowPackageContent}, + "-", + {lang.contextMenuCopy}, + {lang.contextMenuPaste, not _G.clipboard}, + "-", + {lang.contextMenuRename}, + {lang.contextMenuCreateShortcut}, + "-", + {lang.contextMenuUploadToPastebin, true}, + "-", + {lang.contextMenuAddToDock, not somethingCanBeAddedToDock}, + {lang.contextMenuDelete} + ) + else + action = context.menu(eventData[3], eventData[4], + {lang.contextMenuCopy}, + {lang.contextMenuRename}, + {lang.contextMenuCreateShortcut}, + "-", + {lang.contextMenuArchive}, + "-", + {lang.contextMenuDelete} + ) + end + else + if fileFormat == ".pic" then + action = context.menu(eventData[3], eventData[4], + {lang.contextMenuEdit}, + {lang.contextMenuEditInPhotoshop}, + {lang.contextMenuSetAsWallpaper}, + "-", + {lang.contextMenuCopy, false}, + {lang.contextMenuRename}, + {lang.contextMenuCreateShortcut}, + "-", + {lang.contextMenuUploadToPastebin, true}, + "-", + {lang.contextMenuAddToDock, not somethingCanBeAddedToDock}, + {lang.contextMenuDelete, false} + ) + else + action = context.menu(eventData[3], eventData[4], + {lang.contextMenuEdit}, + -- {lang.contextMenuCreateApplication}, + "-", + {lang.contextMenuCopy}, + {lang.contextMenuRename}, + {lang.contextMenuCreateShortcut}, + "-", + {lang.contextMenuUploadToPastebin, true}, + "-", + {lang.contextMenuAddToDock, not somethingCanBeAddedToDock}, + {lang.contextMenuDelete} + ) + end + end + + if action == lang.contextMenuEdit then + ecs.prepareToExit() + MineOSCore.safeLaunch("bin/edit.lua", icon.path) + executeMethod(fullRefreshMethod) + elseif action == lang.contextMenuEditInPhotoshop then + MineOSCore.safeLaunch("MineOS/Applications/Photoshop.app/Photoshop.lua", "open", icon.path) + executeMethod(fullRefreshMethod) + -- buffer.paste(1, 1, oldPixelsOfFullScreen) + -- drawAll(true) + elseif action == lang.contextMenuAddToFavourites then + -- addToFavourites(fs.name(path), path) + computer.pushSignal("finderFavouriteAdded", icon.path) + executeMethod(drawAllMethod) + elseif action == lang.contextMenuShowPackageContent then + executeMethod(changeCurrentPathMethod) + executeMethod(drawAllMethod) + -- changePath(path) + -- drawAll() + elseif action == lang.contextMenuCopy then + _G.clipboard = icon.path + executeMethod(drawAllMethod) + elseif action == lang.contextMenuPaste then + ecs.copy(_G.clipboard, fs.path(icon.path) or "") + executeMethod(drawAllMethod) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll() + elseif action == lang.contextMenuDelete then + fs.remove(icon.path) + executeMethod(drawAllMethod) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll() + elseif action == lang.contextMenuRename then + ecs.rename(icon.path) + executeMethod(drawAllMethod) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll() + elseif action == lang.contextMenuCreateShortcut then + ecs.createShortCut(fs.path(icon.path).."/"..ecs.hideFileFormat(fs.name(icon.path))..".lnk", icon.path) + executeMethod(drawAllMethod) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll() + elseif action == lang.contextMenuArchive then + -- ecs.info("auto", "auto", "", "Архивация файлов...") + archive.pack(ecs.hideFileFormat(fs.name(icon.path))..".pkg", icon.path) + executeMethod(drawAllMethod) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll() + elseif action == lang.contextMenuUploadToPastebin then + MineOSCore.safeLaunch("MineOS/Applications/Pastebin.app/Pastebin.lua", "upload", icon.path) + executeMethod(fullRefreshMethod) + -- shell.execute("MineOS/Applications/Pastebin.app/Pastebin.lua upload " .. path) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll(true) + elseif action == lang.contextMenuSetAsWallpaper then + --ecs.error(path) + ecs.createShortCut("MineOS/System/OS/Wallpaper.lnk", icon.path) + computer.pushSignal("OSWallpaperChanged") + return true + -- buffer.paste(1, 1, oldPixelsOfFullScreen) + -- buffer.draw() + elseif action == lang.contextMenuCreateApplication then + ecs.newApplicationFromLuaFile(icon.path, fs.path(icon.path) or "") + executeMethod(drawAllMethod) + -- getFileList(workPathHistory[currentWorkPathHistoryElement]) + -- drawAll() + else + buffer.paste(icon.x, icon.y, oldPixelsOfIcon) + buffer.draw() + end +end + +function MineOSCore.iconClick(icon, eventData, selectionColor, selectionTransparency, iconTextColor, clickSleepDelay, somethingCanBeAddedToDock, drawAllMethod, fullRefreshMethod, changeCurrentPathMethod) + local fileFormat = ecs.getFileFormat(icon.path) + local oldPixelsOfIcon = MineOSCore.iconSelect(icon, selectionColor, selectionTransparency, iconTextColor) + local dataToReturn + + if eventData[5] == 0 then + os.sleep(clickSleepDelay) + dataToReturn = MineOSCore.iconLeftClick(icon, oldPixelsOfIcon, fileFormat, drawAllMethod, fullRefreshMethod, changeCurrentPathMethod) + else + dataToReturn = MineOSCore.iconRightClick(icon, oldPixelsOfIcon, eventData, fileFormat, somethingCanBeAddedToDock, drawAllMethod, fullRefreshMethod, changeCurrentPathMethod) + end + return dataToReturn +end + +function MineOSCore.emptyZoneClick(eventData, workPath, drawAllMethod) + local action = context.menu(eventData[3], eventData[4], {lang.contextMenuNewFile}, {lang.contextMenuNewFolder}, {lang.contextMenuNewApplication}, "-", {lang.contextMenuPaste, (_G.clipboard == nil), "^V"}) + if action == lang.contextMenuNewFile then + ecs.newFile(workPath) + executeMethod(drawAllMethod) + elseif action == lang.contextMenuNewFolder then + ecs.newFolder(workPath) + executeMethod(drawAllMethod) + elseif action == lang.contextMenuPaste then + ecs.copy(_G.clipboard, workPath) + executeMethod(drawAllMethod) + elseif action == lang.contextMenuNewApplication then + ecs.newApplication(workPath) + executeMethod(drawAllMethod) + end +end + + +----------------------------------------------------------------------------------------------------------------------------------- + +-- MineOSCore.loadIcons() +-- buffer.start() + +-- buffer.clear(0x262626) +-- MineOSCore.drawIconField(2, 2, 5, 5, 1, 25, 2, 1, "lib/", "type", true, 0xFFFFFF) +-- buffer.draw(true) + +----------------------------------------------------------------------------------------------------------------------------------- + +return MineOSCore + + + + + diff --git a/lib/doubleBuffering.lua b/lib/doubleBuffering.lua index 1dca6f82..5dbf2f00 100644 --- a/lib/doubleBuffering.lua +++ b/lib/doubleBuffering.lua @@ -86,7 +86,7 @@ end -- Получить информацию о пикселе из буфера function buffer.get(x, y) local index = convertCoordsToIndex(x, y) - if x >= buffer.drawLimit.x1 and y >= buffer.drawLimit.y1 and x <= buffer.drawLimit.x2 and y <= buffer.drawLimit.y2 then + if x >= 1 and y >= 1 and x <= buffer.screen.width and y <= buffer.screen.height then return buffer.screen.new[index], buffer.screen.new[index + 1], buffer.screen.new[index + 2] else error("Невозможно получить указанные значения, так как указанные координаты лежат за пределами экрана.\n")