Debian Codegraph @

CorsixTH/Lua/dialogs/tree_ctrl.lua

raw
1 --[[ Copyright (c) 2010 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 --! Interface for items within a UI tree control
22 class "TreeNode"
23
24 ---@type TreeNode
25 local TreeNode = _G["TreeNode"]
26
27 function TreeNode:TreeNode()
28 self.is_expanded = false
29 self.num_visible_descendants = 0
30 end
31
32 --! Get the number of childrem which the item has
33 function TreeNode:getChildCount()
34 error("To be implemented in subclasses")
35 end
36
37 --! Query if the item has any children at all.
38 --! The simple way of doing this is checking if getChildCount() is non-zero,
39 -- but often this can be implemented in a more efficient manner.
40 function TreeNode:hasChildren()
41 return self:getChildCount() ~= 0
42 end
43
44 --! Get a child of the item.
45 --!param idx (integer) An integer between 1 and getChildCount() (inclusive).
46 function TreeNode:getChildByIndex(idx)
47 error("To be implemented in subclasses")
48 end
49
50 --! Given a child of the item, determine which index it is
51 --!param child (TreeNode) A value returned from getChildByIndex()
52 function TreeNode:getIndexOfChild(child)
53 error("To be implemented in subclasses")
54 end
55
56 --! Get the text to be displayed for the item
57 function TreeNode:getLabel()
58 error("To be implemented in subclasses")
59 end
60
61 --! Get the item's parent, if it has one
62 function TreeNode:getParent()
63 return self.parent
64 end
65
66 --! Get the tree control within which the item is displayed
67 function TreeNode:getControl()
68 return self.control or self:getParent():getControl()
69 end
70
71 --! Query whether the item's children are visible
72 function TreeNode:isExpanded()
73 return self.is_expanded
74 end
75
76 --! Get the background colour for when the item is highlighted
77 function TreeNode:getHighlightColour(canvas)
78 return nil
79 end
80
81 --! Get the background colour for when the item is selected
82 function TreeNode:getSelectColour(canvas)
83 return canvas:mapRGB(174, 166, 218)
84 end
85
86 --! Make the children of the item visible
87 function TreeNode:expand()
88 if self.is_expanded then return end
89 self.is_expanded = true
90 self.num_visible_descendants = 0
91 for i = 1, self:getChildCount() do
92 self.num_visible_descendants = self.num_visible_descendants +
93 1 + self:getChildByIndex(i).num_visible_descendants
94 end
95 local parent = self:getParent()
96 while parent do
97 parent.num_visible_descendants = parent.num_visible_descendants +
98 self.num_visible_descendants
99 parent = parent:getParent()
100 end
101 self:getControl():onNumVisibleNodesChange()
102 end
103
104 --! Make the children of the item invisible
105 function TreeNode:contract()
106 if not self.is_expanded then return end
107 self.is_expanded = false
108 local parent = self:getParent()
109 while parent do
110 parent.num_visible_descendants = parent.num_visible_descendants -
111 self.num_visible_descendants
112 parent = parent:getParent()
113 end
114 self.num_visible_descendants = 0
115 self:getControl():onNumVisibleNodesChange()
116 end
117
118 --! The number of visible items in the set of this item and all its descendants
119 function TreeNode:numVisibleDescendants()
120 if self.hidden then
121 return self.num_visible_descendants
122 else
123 return self.num_visible_descendants + 1
124 end
125 end
126
127 --! Get the depth from the root item to this item.
128 --! The root item has level 0, its direct children have level 1, etc.
129 function TreeNode:getLevel()
130 local level = self.level
131 if not level then
132 local parent = self:getParent()
133 if parent then
134 level = parent:getLevel() + 1
135 else
136 level = 0
137 end
138 self.level = level
139 end
140 return level
141 end
142
143 --! Get the previous item in the on-screen display order
144 function TreeNode:getPrevVisible()
145 local parent = self:getParent()
146 if not parent then
147 return
148 end
149 local idx = parent:getIndexOfChild(self)
150 if idx == 1 then
151 return parent
152 else
153 local prev = parent:getChildByIndex(idx - 1)
154 while prev:isExpanded() do
155 if not prev:hasChildren() then
156 break
157 else
158 prev = prev:getChildByIndex(prev:getChildCount())
159 end
160 end
161 return prev
162 end
163 end
164
165 --! Get the next item in the on-screen display order
166 function TreeNode:getNextVisible()
167 if self:isExpanded() and self:hasChildren() then
168 return self:getChildByIndex(1)
169 end
170 while true do
171 local parent = self:getParent()
172 if not parent then
173 return
174 end
175 local idx = parent:getIndexOfChild(self)
176 if idx == parent:getChildCount() then
177 self = parent
178 else
179 return parent:getChildByIndex(idx + 1)
180 end
181 end
182 end
183
184 --! A tree node representing a file (or directory) in the physical file-system.
185 class "FileTreeNode" (TreeNode)
186
187 ---@type FileTreeNode
188 local FileTreeNode = _G["FileTreeNode"]
189
190 local pathsep = package.config:sub(1, 1)
191
192 function FileTreeNode:FileTreeNode(path)
193 self:TreeNode()
194 if path:sub(-1) == pathsep and path ~= pathsep then
195 path = path:sub(1, -2)
196 end
197 self.path = path
198 self.children = {}
199 self.has_looked_for_children = false
200 -- Default sorting is by name
201 self.sort_by = "name"
202 self.order = "ascending"
203 end
204
205 function FileTreeNode:isDirectory()
206 return lfs.attributes(self.path, "mode") == "directory"
207 end
208
209 ---
210 --@param <file_name_filter> (optional) return the most recently modified child file which has this string in its name.
211 --@return nil if no child file is found otherwise return the FileTreedNode for mostly recently modified child file.
212 function FileTreeNode:getMostRecentlyModifiedChildFile(file_name_filter)
213 self:checkForChildren()
214 self:reSortChildren("date", "descending")
215 local most_recently_mod_child_dir_file = nil
216 local root_child = nil
217 --A. Search for files matching the file name filter in the root directory and its child directories:
218 for i = 1, self:getChildCount(), 1 do
219 root_child = self:getChildByIndex(i)
220 -- 1. Get the most recently modified child directory file which matches the name filter:
221 if root_child:isDirectory() then
222 local current_child_dir_file = root_child:getMostRecentlyModifiedChildFile(file_name_filter)
223 if current_child_dir_file ~= nil then
224 if most_recently_mod_child_dir_file == nil then
225 most_recently_mod_child_dir_file = current_child_dir_file
226 elseif current_child_dir_file:getLastModification() > most_recently_mod_child_dir_file:getLastModification() then
227 most_recently_mod_child_dir_file = current_child_dir_file
228 end
229 end
230
231 -- Sort always puts directories first so when this else closure is reached in this iterative for loop
232 -- all the sub directories will have been checked:
233 else
234 -- 2. Get the most recently modified root directory file which matches the name filter:
235 local matches_filter = true
236 if(file_name_filter) then
237 matches_filter = string.find(root_child:getLabel(), file_name_filter)
238 end
239 -- End this for loop to begin step B:
240 if matches_filter then
241 break
242 end
243 end
244 root_child = nil
245 end
246 --B. Return the most recently modified file or nil if no file matching the name filter was found:
247 if most_recently_mod_child_dir_file then
248 if root_child then
249 if root_child:getLastModification() > most_recently_mod_child_dir_file:getLastModification() then
250 return root_child
251 end
252 end
253 return most_recently_mod_child_dir_file
254 elseif root_child then
255 return root_child
256 else
257 return nil
258 end
259 end
260
261 function FileTreeNode:childPath(item)
262 if self.path:sub(-1, -1) == pathsep then
263 return self.path .. item
264 else
265 return self.path .. pathsep .. item
266 end
267 end
268
269 function FileTreeNode:hasChildren()
270 if self.has_looked_for_children then
271 return #self.children ~= 0
272 elseif self.has_children == nil then
273 if self:getLevel() == 0 then
274 -- Assume root level things have children until we really need to check
275 return true
276 end
277 self.has_children = false
278 -- Only directories have children.
279 if lfs.attributes(self.path, "mode") ~= "directory" then
280 return false
281 end
282 local status, err, dir_obj = pcall(lfs.dir, self.path)
283 if not status then
284 print("Error while fetching children for " .. self.path .. ": " .. err)
285 else
286 for item in dir_obj.next, dir_obj do
287 if self:isValidFile(item) then
288 self.has_children = true
289 break
290 end
291 end
292 dir_obj:close()
293 end
294 end
295 return self.has_children
296 end
297
298 --! Returns whether the given file name is valid
299 -- in this tree. Override for desired behaviour.
300 function FileTreeNode:isValidFile(name)
301 return name ~= "." and name ~= ".."
302 end
303
304 function FileTreeNode:createNewNode(path)
305 return FileTreeNode(path)
306 end
307
308 function FileTreeNode:expand()
309 TreeNode.expand(self)
310 self:reSortChildren(self.sort_by, self.order)
311 end
312
313 local function sort_by_key(t1, t2)
314 local second_mode = lfs.attributes(t2.path, "mode") == "directory"
315 if lfs.attributes(t1.path, "mode") == "directory" then
316 if second_mode then
317 if t1.order == "ascending" then
318 return t1.sort_key < t2.sort_key
319 else
320 return t1.sort_key > t2.sort_key
321 end
322 else
323 return true
324 end
325 else
326 if second_mode then
327 return false
328 else
329 if t1.order == "ascending" then
330 return t1.sort_key < t2.sort_key
331 else
332 return t1.sort_key > t2.sort_key
333 end
334 end
335 end
336 end
337
338 --! Sorts the node and its children either by date or by name.
339 --!param sort_by What to sort by. Either "name" or "date".
340 --!param order If the ordering should be "ascending" or "descending".
341 function FileTreeNode:reSortChildren(sort_by, order)
342 for _, child in ipairs(self.children) do
343 if sort_by == "date" then
344 child.sort_key = lfs.attributes(child.path, "modification")
345 child.sort_by = sort_by
346 child.order = order
347 elseif sort_by == "name" then
348 child.sort_key = child:getLabel():lower()
349 child.sort_by = sort_by
350 child.order = order
351 else
352 -- No sorting
353 return
354 end
355 end
356 table.sort(self.children, sort_by_key)
357 for i, child in ipairs(self.children) do
358 self.children[child] = i
359 child:reSortChildren(sort_by, order)
360 end
361 end
362
363 function FileTreeNode:checkForChildren()
364 if not self.has_looked_for_children then
365 self.has_looked_for_children = true
366 if self.has_children == false then
367 -- Already checked and found nothing
368 return
369 end
370 for item in lfs.dir(self.path) do
371 local path = self:childPath(item)
372 if self:isValidFile(item) then
373 local node = self:createNewNode(path)
374 node.sort_key = item:lower()
375 self.children[#self.children + 1] = node
376 end
377 end
378
379 for i, child in ipairs(self.children) do
380 self.children[child] = i
381 self.children[child.sort_key] = i
382 child.parent = self
383 end
384 end
385 end
386
387 function FileTreeNode:getHighlightColour(canvas)
388 local highlight_colour = self.highlight_colour
389 if highlight_colour == nil then
390 highlight_colour = false
391 if type(self.filter_by) == "table" then
392 for _, ext in ipairs(self.filter_by) do
393 if string.sub(self.path:lower(), -string.len(ext)) == ext then
394 self.is_valid_file = true
395 highlight_colour = canvas:mapRGB(0, 255, 0)
396 end
397 end
398 elseif self.filter_by and string.sub(self.path:lower(), -string.len(self.filter_by)) == self.filter_by then
399 self.is_valid_file = true
400 highlight_colour = canvas:mapRGB(0, 255, 0)
401 end
402 self.highlight_colour = highlight_colour
403 end
404 return highlight_colour or nil
405 end
406
407 function FileTreeNode:getChildCount()
408 self:checkForChildren()
409 return #self.children
410 end
411
412 function FileTreeNode:getChildByIndex(idx)
413 self:checkForChildren()
414 return self.children[idx]
415 end
416
417 function FileTreeNode:getIndexOfChild(child)
418 return self.children[child]
419 end
420
421 function FileTreeNode:getLabel()
422 local label = self.label
423 if not label then
424 local parent = self:getParent()
425 if parent and parent.path then
426 if parent.path:sub(-1, -1) == pathsep then
427 label = self.path:sub(#parent.path + 1, -1)
428 else
429 label = self.path:sub(#parent.path + 2, -1)
430 end
431 else
432 label = self.path
433 end
434 self.label = label
435 end
436 return label
437 end
438
439 function FileTreeNode:getLastModification()
440 return lfs.attributes(self.path, "modification")
441 end
442
443 --! Selects an item. By default everything selected is valid. Can be overridden
444 -- by inheriting classes.
445 function FileTreeNode:select()
446 self.is_valid_directory = true
447 end
448
449 --! A tree node which can be used as a root node to give the effect of having
450 -- multiple root nodes.
451 class "DummyRootNode" (TreeNode)
452
453 ---@type DummyRootNode
454 local DummyRootNode = _G["DummyRootNode"]
455
456 --!param roots (array) An array of `TreeNode`s which should be displayed as
457 -- root nodes.
458 function DummyRootNode:DummyRootNode(roots)
459 self:TreeNode()
460 self.children = {}
461 for i, child in ipairs(roots) do
462 self.children[i] = child
463 self.children[child] = i
464 child.parent = self
465 end
466 self.level = -1 -- to make children level 0
467 self.hidden = true
468 end
469
470 function DummyRootNode:getChildCount()
471 return #self.children
472 end
473
474 function DummyRootNode:getChildByIndex(idx)
475 return self.children[idx]
476 end
477
478 function DummyRootNode:getIndexOfChild(child)
479 return self.children[child]
480 end
481
482 --! A control (to be placed on a window) which allows the user to navigate a
483 -- tree of items and select one item from it.
484 class "TreeControl" (Window)
485
486 ---@type TreeControl
487 local TreeControl = _G["TreeControl"]
488
489 --!param root (TreeNode) The single root node of the tree (use a `DummyRootNode`
490 -- here if multiple root nodes are desired).
491 --!param x (integer) The X-position, in pixels, where the control should start
492 -- within its parent.
493 --!param y (integer) The Y-position, in pixels, where the control should start
494 -- within its parent.
495 --!param width (integer) The width, in pixels, of the control.
496 --!param height (integer) The height, in pixels, of the control.
497 --!param col_bg (table) The background colour of the control - this should be
498 -- a table with `red`, `green`, and `blue` fields, each an integer between 0
499 -- and 255.
500 --!param col_fg (table) The colour used for the scrollbar and highlighted items.
501 function TreeControl:TreeControl(root, x, y, width, height, col_bg, col_fg, y_offset, has_font)
502 -- Setup the base window
503 self:Window()
504 self.x = x
505 self.y = y
506 self.width = width
507 self.height = height
508 self.y_offset = y_offset or 0
509
510 -- Load the graphical resources
511 local gfx = TheApp.gfx
512 if not has_font then
513 self.font = gfx:loadBuiltinFont()
514 else
515 self.font = TheApp.gfx:loadFontAndSpriteTable("QData", "Font01V", nil, nil, { apply_ui_scale = true })
516 end
517 self.tree_sprites = gfx:loadSpriteTable("Bitmap", "tree_ctrl", true,
518 gfx:getPalette("tree_ctrl.pal"))
519
520 -- Calculate sizes and counts
521 local scrollbar_width = 20
522 self.row_height = 14
523 self.tree_rect = {
524 x = 0,
525 y = 0,
526 w = width - scrollbar_width,
527 h = height - height % self.row_height,
528 }
529 self.num_rows = (self.tree_rect.h - self.y_offset) / self.row_height
530 self:addBevelPanel(0, 0, width, height, col_bg).lowered = true
531 local scrollbar_base = self:addBevelPanel(width - scrollbar_width, 0,
532 scrollbar_width, height, col_bg)
533 scrollbar_base.lowered = true
534 self.scrollbar = scrollbar_base:makeScrollbar(col_fg,
535 --[[persistable:tree_ctrl_scrollbar_callback]] function()
536 self:onScroll()
537 end, 1, 1, self.num_rows)
538 self.tree_root = root
539 if root.hidden then
540 self.first_visible_node = root:getChildByIndex(1)
541 else
542 self.first_visible_node = root
543 end
544 root.control = self
545 self.first_visible_ordinal = 1
546 root:expand()
547 end
548
549
550 function TreeControl:hitTestTree(x, y)
551 local s = TheApp.config.ui_scale
552 local rect = self.tree_rect
553 x = x - rect.x * s
554 y = y - rect.y * s - self.y_offset * s
555 if 0 <= x and 0 <= y and x < rect.w * s and y < rect.h * s then
556 local n = math.floor(y / (self.row_height * s))
557 local node = self.first_visible_node
558 while n ~= 0 and node do
559 node = node:getNextVisible()
560 n = n - 1
561 end
562 if n == 0 then
563 if node then
564 local level = node:getLevel()
565 if x > level * 14 * s then
566 if x < (level+1) * 14 * s then
567 return node, true
568 else
569 return node, false
570 end
571 end
572 end
573 end
574 end
575 end
576
577 function TreeControl:onMouseMove(x, y, dx, dy)
578 local redraw = Window.onMouseMove(self, x, y)
579 local node, expand = self:hitTestTree(x, y)
580 if expand and self.highlighted_node ~= nil then
581 self.highlighted_node = nil
582 return redraw
583 elseif not expand and node ~= self.highlighted_node then
584 self.highlighted_node = node
585 return redraw
586 end
587 return redraw
588 end
589
590 function TreeControl:onMouseDown(button, x, y)
591 local redraw = Window.onMouseDown(self, button, x, y)
592 if button ~= 4 and button ~= 5 then
593 local s = TheApp.config.ui_scale
594 -- NB: 4 and 5 are scrollwheel
595 self.mouse_down_in_self = false
596 if 0 <= x and 0 <= y and x < self.width * s and y < self.height * s then
597 self.mouse_down_in_self = true
598 redraw = true
599 end
600 end
601 return redraw
602 end
603
604 --! Function to handle (final) selection by user that needs to feed back data to
605 --! another dialog.
606 --!param callback (function) Code to execute on trigger
607 --!return self
608 function TreeControl:setSelectCallback(callback)
609 self.select_callback = callback
610 return self
611 end
612
613 --! Function for where an action in the file tree needs to feed back data to another
614 --! dialog. Its specific usage should be noted in the parent element
615 --!param callback (function) Code to execute on trigger
616 --!return self
617 function TreeControl:setValueChangeCallback(callback)
618 self.val_change_callback = callback
619 return self
620 end
621
622 function TreeControl:onMouseUp(button, x, y)
623 local redraw = Window.onMouseUp(self, button, x, y)
624 local node, expand = self:hitTestTree(x, y)
625 if self.mouse_down_in_self and node then
626 -- Expand/collapse directory
627 if expand then
628 if node:hasChildren() then
629 if node:isExpanded() then
630 node:contract()
631 else
632 node:expand()
633 end
634 redraw = true
635 end
636 -- Clicking on already highlighted file
637 elseif self.selected_node == node and self.select_callback then
638 self.select_callback(node)
639 redraw = true
640 -- A new file has been selected (not highlighted)
641 else
642 self.selected_node = node
643 if self.val_change_callback then
644 self.val_change_callback(node, node:getLabel())
645 end
646 node:select()
647 redraw = true
648 end
649 end
650 self.mouse_down_in_self = false
651 return redraw
652 end
653
654 function TreeControl:onMouseWheel(x, y)
655 self.scrollbar:setXorY(self.scrollbar:getXorY() - y * 8)
656 end
657
658 function TreeControl:onNumVisibleNodesChange()
659 self.scrollbar:setRange(1, self.tree_root:numVisibleDescendants(),
660 self.num_rows, self.first_visible_ordinal)
661 end
662
663 function TreeControl:onScroll()
664 if self.scrollbar.value > self.first_visible_ordinal then
665 for _ = 1, self.scrollbar.value - self.first_visible_ordinal do
666 self.first_visible_node = self.first_visible_node:getNextVisible()
667 end
668 elseif self.scrollbar.value < self.first_visible_ordinal then
669 for _ = 1, self.first_visible_ordinal - self.scrollbar.value do
670 self.first_visible_node = self.first_visible_node:getPrevVisible()
671 end
672 end
673 self.first_visible_ordinal = self.scrollbar.value
674 end
675
676 --! Override this function if a certain row should have certain text
677 -- or additional flavour to it.
678 function TreeControl:drawExtraOnRow(canvas, node, x, y)
679 end
680
681 function TreeControl:draw(canvas, x, y)
682 Window.draw(self, canvas, x, y)
683 local s = TheApp.config.ui_scale
684 x = x + self.x * s + self.tree_rect.x * s
685 y = y + self.y * s + self.tree_rect.y * s + self.y_offset * s
686
687 local node = self.first_visible_node
688 local num_nodes_drawn = 0
689 while node and num_nodes_drawn < self.num_rows do
690 local level = node:getLevel()
691 for i = 0, level - 1 do
692 self.tree_sprites:draw(canvas, 1, x + i * 14 * s, y, { scaleFactor = s })
693 end
694
695 if node == self.highlighted_node then
696 local offset = (level + 1) * 14
697 local colour = node:getHighlightColour(canvas) or self.scrollbar.slider.colour
698 canvas:drawRect(colour, x + offset * s - s, y, self.tree_rect.w * s - offset * s - s, self.row_height * s)
699 end
700 if node == self.selected_node then
701 local offset = (level + 1) * 14
702 local colour = node:getSelectColour(canvas) or self.scrollbar.slider.colour
703 canvas:drawRect(colour, x + offset * s - s, y, self.tree_rect.w * s - offset * s - s, self.row_height * s)
704 end
705
706 local icon
707 if not node:hasChildren() then
708 icon = 2
709 elseif node:isExpanded() then
710 icon = 4
711 else
712 icon = 3
713 end
714 self.tree_sprites:draw(canvas, icon, x + level * 14 * s, y, { scaleFactor = s })
715 self.font:draw(canvas, node:getLabel(), x + (level + 1) * 14 * s, y + 2 * s)
716 self:drawExtraOnRow(canvas, node, x, y)
717 y = y + self.row_height * s
718 num_nodes_drawn = num_nodes_drawn + 1
719 node = node:getNextVisible()
720 end
721 end