SelectionInTreeView.st
author tz
Sun, 22 Feb 1998 14:36:02 +0100
changeset 773 b3596157f97d
parent 771 0c57b324cf4d
child 774 98d6c7e3e851
permissions -rw-r--r--
register the icons and put them into a caching dict

"
 COPYRIGHT (c) 1997 by eXept Software AG / Claus Gittinger
              All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"


SelectionInListView subclass:#SelectionInTreeView
	instanceVariableNames:'validateDoubleClickBlock selectionHolder rootHolder imageWidth
		showLines listOfNodes imageInset textInset labelOffsetY lineMask
		lineColor openIndicator computeResources closeIndicator showRoot
		extentOpenIndicator extentCloseIndicator showDirectoryIndicator
		showDirectoryIndicatorForRoot indicatorExtentDiv2 imageOpened
		imageClosed imageItem discardMotionEvents registeredImages'
	classVariableNames:'ImageOpened ImageClosed ImageItem OpenIndicator CloseIndicator'
	poolDictionaries:''
	category:'Views-Text'
!

!SelectionInTreeView class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1997 by eXept Software AG / Claus Gittinger
              All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"

!

documentation
"
    somewhat like a SelectionInListView; but specialized for hierarchical (i.e. tree-like)
    lists and adds the functions to show/hide subtrees. 
    Requires SelectionInTree as model and TreeItem (or compatible) list entries.

    This class obsoletes SelectionInTreeView, which is no longer
    maintained but kept for backward compatibility.


    [see also:]
        SelectionInTree
        TreeItem
        SelectionInTreeView
        SelectionInListView
        FileSelectionTree

    [author:]
        Claus Atzkern
"

!

examples
"
    shows the tree of smalltalk classes:
                                                                        [exBegin]
      |top sel|

      top := StandardSystemView new; extent:300@300.
      sel := SelectionInTreeView new.
      sel root:(TreeItem newAsTreeFromSmalltalkClass:Object).
      sel action:[:nr | Transcript show:'selected:'; showCR:nr].
      top add:(ScrollableView forView:sel) in:((0.0 @ 0.0 ) corner:( 1.0 @ 1.0)).
      top open.
                                                                        [exEnd]



    same, including nil-subclasses (i.e. really all classes):
                                                                        [exBegin]
      |top sel|

      top := StandardSystemView new; extent:300@300.
      sel := SelectionInTreeView new.
      sel root:(TreeItem newAsTreeFromSmalltalkClass:nil).
      sel action:[:nr | Transcript show:'selected:'; showCR:nr].
      sel lineColor:(Color red).
      top add:(ScrollableView forView:sel) in:((0.0 @ 0.0 ) corner:( 1.0 @ 1.0)).
      top open.
                                                                        [exEnd]



    shows the tree of smalltalk classes; show directory indication and no
    lines.
                                                                        [exBegin]
      |top sel|

      top := StandardSystemView new; extent:300@300.
      sel := SelectionInTreeView new.
      sel showLines:false.
      sel showDirectoryIndicator:true.
      sel root:(TreeItem newAsTreeFromSmalltalkClass:Object).
      sel action:[:nr | Transcript show:'selected:'; showCR:nr].
      top add:(ScrollableView forView:sel) in:((0.0 @ 0.0 ) corner:( 1.0 @ 1.0)).
      top open.
                                                                        [exEnd]
"


! !

!SelectionInTreeView class methodsFor:'constants'!

minImageInset
    "returns minimum inset from directory indication to image
    "
  ^ 6


! !

!SelectionInTreeView class methodsFor:'default images'!

closeIndicator
    <resource: #fileImage>

    CloseIndicator isNil ifTrue:[
        CloseIndicator := Image fromFile:('xpmBitmaps/plus.xpm').
    ].
  ^ CloseIndicator
"
CloseIndicator := nil
"

    "Modified: / 29.10.1997 / 03:36:00 / cg"
!

imageClosed
    <resource: #fileImage>

    ImageClosed isNil ifTrue:[
        ImageClosed := Image fromFile:('xpmBitmaps/document_images/tiny_yellow_dir.xpm').
    ].
  ^ ImageClosed
"
ImageClosed := nil
"

    "Modified: / 29.10.1997 / 03:36:05 / cg"
!

imageItem
    <resource: #fileImage>

    ImageItem isNil ifTrue:[
        ImageItem := Image fromFile:('xpmBitmaps/document_images/tiny_file_plain.xpm')  

    ].
  ^ ImageItem
"
ImageItem := nil
"

    "Modified: / 29.10.1997 / 03:36:10 / cg"
!

imageOpened
    <resource: #fileImage>

    ImageOpened isNil ifTrue:[
        ImageOpened := Image fromFile:('xpmBitmaps/document_images/tiny_yellow_dir_open.xpm').

    ].
  ^ ImageOpened
"
ImageOpened := nil
"

    "Modified: / 29.10.1997 / 03:36:15 / cg"
!

openIndicator
    <resource: #fileImage>

    OpenIndicator isNil ifTrue:[
        OpenIndicator := Image fromFile:('xpmBitmaps/minus.xpm').
    ].
  ^ OpenIndicator
"
OpenIndicator := nil
"

    "Modified: / 29.10.1997 / 03:36:21 / cg"
! !

!SelectionInTreeView methodsFor:'accessing'!

lineColor
    "returns user configured line color or nil
    "
    ^ lineColor

!

lineColor:aColor
    "returns user configured line color or nil
    "
    |col|

    col := aColor = fgColor ifTrue:[nil] ifFalse:[aColor].

    col = lineColor ifFalse:[
        lineColor := col.

        shown ifTrue:[
            lineColor notNil ifTrue:[lineColor := lineColor on:device].
            self invalidate
        ]
    ]
!

nodeAtIndex:anIndex
    "returns node at an index or nil
    "
    (anIndex notNil and:[anIndex ~~ 0 and:[anIndex <= listOfNodes size]]) ifTrue:[
        ^ listOfNodes at:anIndex
    ].
  ^ nil
!

root
    "gets the root of the model; the first item into list.
    "
    ^ self nodeAtIndex:1
!

root:aRoot
    "sets the root of the model; the first item into list.
    "
    aRoot notNil ifTrue:[aRoot expand].
    model root:aRoot
!

textInset
    "get the left inset of the text label
    "
    ^ textInset
!

textInset:anInset
    "set the left inset of the text label
    "
    anInset ~~ textInset ifTrue:[
        anInset >= 0 ifTrue:[
            textInset := anInset.
            self invalidate
        ] ifFalse:[
            self error
        ]
    ].
! !

!SelectionInTreeView methodsFor:'accessing-behavior'!

showDirectoryIndicator
    "returns true if directories has an open/closed indicator
    "
  ^ showDirectoryIndicator
!

showDirectoryIndicator:aState
    "set or clear open/closed indicator for directories
    "
    "show or hide lines
    "
    aState ~~ showDirectoryIndicator ifTrue:[
        showDirectoryIndicator := aState.
        self recomputeDirectoryIndicator.
        self invalidate
    ].
!

showDirectoryIndicatorForRoot
    "returns true if root directory has an open/closed indicator if
     the common showDirectoryIndicator is enabled
    "
    ^ showDirectoryIndicatorForRoot
!

showDirectoryIndicatorForRoot:aState
    "true if root directory has an open/closed indicator if
     the common showDirectoryIndicator is enabled
    "
    aState ~~ showDirectoryIndicator ifTrue:[
        showDirectoryIndicatorForRoot := aState.
        self recomputeDirectoryIndicator.
        self invalidate
    ].
!

showLines
    "returns true if lines are shown
    "
  ^ showLines
!

showLines:aState
    "show or hide lines
    "
    aState ~~ showLines ifTrue:[
        showLines := aState.
        self invalidate
    ].
!

showRoot
    "list with or without root
    "
  ^ showRoot
!

showRoot:aState
    "list with or without root
    "
    showRoot ~~ aState ifTrue:[
        model showRoot:(showRoot := aState)
    ].
!

validateDoubleClickBlock
    "set the conditionBlock; this block is evaluated before a doubleClick action
     on a node will be performed. In case of returning false, the doubleClick will
     not be handled.
   "
   ^ validateDoubleClickBlock


!

validateDoubleClickBlock:aOneArgBlock
    "set the conditionBlock; this block is evaluated before a doubleClick action
     on a node will be performed. In case of returning false, the doubleClick will
     not be handled.
   "
   validateDoubleClickBlock := aOneArgBlock


! !

!SelectionInTreeView methodsFor:'accessing-channels'!

rootHolder
    "get the holder which keeps the hierarchical list entry or nil
    "
    ^ rootHolder
!

rootHolder:aValueHolder
    "set the holder which keeps the hierarchical list entry or nil
    "
    rootHolder notNil ifTrue:[
        rootHolder removeDependent:self
    ].
    (rootHolder := aValueHolder) notNil ifTrue:[
        rootHolder addDependent:self.
        self rootFromModel.
    ].
!

selectionHolder
    "get the holder which keeps a list of selected items or nil
    "
    ^ selectionHolder

!

selectionHolder:aHolder
    "set the holder which keeps a list of selected items or nil
    "
    selectionHolder notNil ifTrue:[
        selectionHolder removeDependent:self
    ].

    (selectionHolder := aHolder) notNil ifTrue:[
        selectionHolder addDependent:self.
        self selectionFromModel
    ].

! !

!SelectionInTreeView methodsFor:'accessing-images'!

imageClosed
    "return the value of the instance variable 'imageClosed' (automatically generated)"

    ^ imageClosed

    "Created: 3.7.1997 / 12:34:31 / cg"
!

imageItem
    "return the value of the instance variable 'imageItem' (automatically generated)"

    ^ imageItem

    "Created: 3.7.1997 / 12:34:34 / cg"
!

imageOnDevice:anImage
    "associate iamge to device and clear pixel mask (in case of realized);
     returns the new image.
    "
    |img|

    img := anImage onDevice:device.

    realized ifTrue:[
        img := img clearMaskedPixels
    ].
    ^ img
!

imageOpened
    "return the value of the instance variable 'imageOpened' (automatically generated)"

    ^ imageOpened

    "Created: 3.7.1997 / 12:34:28 / cg"
! !

!SelectionInTreeView methodsFor:'change & update'!

update:something with:aParameter from:aModel
    "one of my models changed its value
    "              
    aModel == rootHolder ifTrue:[
        ^ self rootFromModel
    ].
    aModel == selectionHolder ifTrue:[
        ^ self selectionFromModel   
    ].

    aModel == model ifTrue:[
        something == #list ifTrue:[  
            ^ self getListFromModel
        ]
    ].

    aModel == self selectedNode ifTrue:[
        something == #value ifTrue:[  
            ^ self redrawLine: (self indexOfNode: aModel)
        ]
    ].
    ^ super update:something with:aParameter from:aModel.



! !

!SelectionInTreeView methodsFor:'drawing'!

drawLine:line atX:atX inVisible:visLineNr with:fg and:bg
    self drawFromVisibleLine:visLineNr to:visLineNr with:fg and:bg

!

drawLine:line fromX:x inVisible:visLineNr with:fg and:bg
    self drawFromVisibleLine:visLineNr to:visLineNr with:fg and:bg

!

drawLine:line inVisible:visLineNr with:fg and:bg
    self drawFromVisibleLine:visLineNr to:visLineNr with:fg and:bg

!

drawVisibleLine:visLineNr col:col with:fg and:bg
    self drawFromVisibleLine:visLineNr to:visLineNr with:fg and:bg

!

drawVisibleLine:visLineNr from:startCol to:endCol with:fg and:bg
    self drawFromVisibleLine:visLineNr to:visLineNr with:fg and:bg

!

drawVisibleLine:visLineNr from:startCol with:fg and:bg
    self drawFromVisibleLine:visLineNr to:visLineNr with:fg and:bg

! !

!SelectionInTreeView methodsFor:'drawing basics'!

drawFromVisibleLine:startVisLineNr to:endVisLineNr with:fg and:bg
    "redraw a visible line range with clearing the background
    "
    |y0 y1 sz|

    shown ifTrue:[
        y0  := self yOfVisibleLine:startVisLineNr.
        y0  := y0 - 1.
        sz  := endVisLineNr - startVisLineNr + 1.
        y1  := sz * fontHeight.

    "/  clear rectangle line and set background color
        self paint:bg.
        self fillRectangleX:0 y:y0 width:width height:y1.

        (y1 := self visibleLineToAbsoluteLine:startVisLineNr) notNil ifTrue:[
            self redrawLinesX:0 y:y0 toX:width start:y1 stop:(y1 + sz)
        ]
    ]
!

drawLabelIndex:anIndex atX:x y:yCenter
    "draw text label at x and y centered
    "
    |lbl|

    (lbl := (listOfNodes at:anIndex) name) notNil ifTrue:[
        self displayOpaqueString:lbl x:x y:(yCenter + labelOffsetY).
    ]    
!

redrawLinesX:x0 y:y0 toX:x1 start:start stop:stop
    "redraw from line to line without clearing the background
    "
    |chgdPaint node image isSelected
     ext
     x      "{ Class:SmallInteger }"
     yTop   "{ Class:SmallInteger }"
     yBot   "{ Class:SmallInteger }"
     yCtr   "{ Class:SmallInteger }"
     size   "{ Class:SmallInteger }"
     end    "{ Class:SmallInteger }"
     index  "{ Class:SmallInteger }"
     xCross "{ Class:SmallInteger }"
     xFig   "{ Class:SmallInteger }"
     xStr   "{ Class:SmallInteger }"
     idx    "{ Class:SmallInteger }"
     level
     lv     "{ Class:SmallInteger }"
     figWidthDiv2 "{ Class:SmallInteger }"
    |

    level := nil. "/ to force evaluation of #ifFalse in loop
    yTop  := y0.
    index := start.
    size  := listOfNodes size.
    end   := stop min:size.

    figWidthDiv2 := imageWidth // 2.
    figWidthDiv2 odd ifTrue:[figWidthDiv2 := figWidthDiv2 + 1].
    yCtr := yTop - (fontHeight // 2).

    [index <= end] whileTrue:[
        node := listOfNodes at:index.
        yBot := yTop + fontHeight.
        yCtr := yCtr + fontHeight.

        (lv := node level) == level ifFalse:[
            level  := lv.
            xFig   := self xOfFigureLevel:lv.
            xStr   := self xOfStringLevel:lv.
            xCross := (self xOfFigureLevel:(lv-1)) + figWidthDiv2.
        ].

        (isSelected := self isInSelection:index) ifTrue:[
            self paint:hilightFgColor on:hilightBgColor.
        ] ifFalse:[
            self paint:fgColor on:bgColor.
        ].

        showLines ifTrue:[
            chgdPaint := (lineColor isNil or:[isSelected]) not.

            chgdPaint ifTrue:[
                self paint:lineColor.
            ].

            self mask:lineMask.
            self setMaskOrigin:(self viewOrigin + (0 @ 1) \\ (lineMask extent)).

            xCross < x1 ifTrue:[
                (    ((x := xFig + figWidthDiv2) between:x0 and:x1)
                 and:[node isCollapsable
                 and:[node numberOfChildren ~~ 0]]
                ) ifTrue:[
                    self displayLineFromX:x y:yCtr toX:x y:yBot
                ].

                "/ vertical line from previous to current form
                (     xCross >= x0
                 and:[level ~~ 1
                 and:[node parent children last == node]]
                ) ifTrue:[
                    self displayLineFromX:xCross y:yTop - 1 toX:xCross y:yCtr
                ].

                "/ horizontal line from previous to current form
                (     xFig > x0
                 and:[(level ~~ 1
                  or:[showDirectoryIndicatorForRoot and:[showDirectoryIndicator]])]
                ) ifTrue:[
                    self displayLineFromX:xCross y:yCtr toX:xFig y:yCtr
                ]
            ].

        "/  draw all vertical lines to left side
            xCross >= x0 ifTrue:[
                idx := index.

                [(lv > 0 and:[(idx := idx + 1) <= size])] whileTrue:[
                    (x := (listOfNodes at:idx) level) <= lv ifTrue:[
                        lv := x - 1.

                        (x  := (self xOfFigureLevel:lv) + figWidthDiv2) < x0 ifTrue:[
                            lv := 0
                        ] ifFalse:[
                            x <= x1 ifTrue:[
                                self displayLineFromX:x y:yTop - 1 toX:x y:yBot
                            ]
                        ]
                    ]
                ]
            ].
            self mask:nil.

            chgdPaint ifTrue:[
                isSelected ifTrue:[self paint:hilightFgColor on:hilightBgColor]
                          ifFalse:[self paint:fgColor        on:bgColor]
            ]            
        ].

        "/ draw image
        (image := self figureFor:node) notNil ifTrue:[
            (xFig < x1 and:[(xFig + image width) > x0]) ifTrue:[
                self displayForm:image x:xFig y:(yCtr - (image height // 2))
            ]
        ].

        "/ draw text label
        xStr < x1 ifTrue:[
            self drawLabelIndex:index atX:xStr y:yCtr .
        ].

        "/ draw directory indicator

        (showDirectoryIndicator and:[node showIndicator]) ifTrue:[
            (level ~~ 1 or:[showDirectoryIndicatorForRoot]) ifTrue:[
                node isCollapsable ifTrue:[
                    image := openIndicator.
                    ext := extentOpenIndicator.
                ] ifFalse:[
                    image := closeIndicator.
                    ext := extentCloseIndicator.
                ].
                idx := ext x.

                (xCross - idx < x1 and:[xCross + idx > x0]) ifTrue:[
                    self displayForm:image x:(xCross - idx) y:(yCtr - ext y)
                ]
            ]
        ].
        "/ setup next line
        index := index + 1.
        yTop  := yBot.
    ]
!

redrawX:x y:y width:w height:h
    "a region must be redrawn"

    |saveClip
     y0       "{ Class:SmallInteger }"
     y1       "{ Class:SmallInteger }"
     visStart "{ Class:SmallInteger }"
     visEnd   "{ Class:SmallInteger }"
     startLn
     stopLn   "{ Class:SmallInteger }"
     maxY     "{ Class:SmallInteger }"
     startY   "{ Class:SmallInteger }"|

    shown ifFalse:[^ self].

    visStart := self visibleLineOfY:(y + 1).
    visEnd   := self visibleLineOfY:(y + h).
    startLn  := self visibleLineToAbsoluteLine:visStart.

    saveClip := clipRect.
    self clippingRectangle:(Rectangle left:x top:y width:w height:h).
    self paint:bgColor.
    self fillRectangleX:x y:y width:w height:h.

    startLn notNil ifTrue:[
        startY := (self yOfVisibleLine:visStart) -1.
        stopLn := startLn + visEnd - visStart.

        saveClip := clipRect.
        self clippingRectangle:(Rectangle left:x top:y width:w height:h).

        self hasSelection ifTrue:[
            maxY := y + h.

            self selectionDo:[:i|
                (i between:startLn and:stopLn) ifTrue:[
                    self paint:hilightBgColor.
                    y0 := (startY + (i - startLn * fontHeight)).
                    y1 := (y0 + fontHeight) min:maxY.
                    y0 := y0 max:y.
                    self fillRectangleX:x y:y0 width:w height:y1 - y0
                ]
            ]
        ].
        self redrawLinesX:x y:startY toX:(x + w) start:startLn stop:stopLn.
    ].
    self clippingRectangle:saveClip.

! !

!SelectionInTreeView methodsFor:'enumerating'!

detectNode:aOneArgBlock
    "evaluate the argument, aBlock for each node in the list until
     the block returns true; in this case return the node which caused
     the true evaluation. If none node is detected, nil is returned.
    "
  ^ listOfNodes detect:aOneArgBlock ifNone:nil
!

selectedNodesDo:aOneArgBlock
    "evaluate the block on each node selected
    "
    self selectionDo:[:i| aOneArgBlock value:(listOfNodes at:i) ]
! !

!SelectionInTreeView methodsFor:'event handling'!

buttonMotion:buttonMask x:x y:y
    "mouse-move while button was pressed - handle selection changes"

    discardMotionEvents ifFalse:[
        super buttonMotion:buttonMask x:x y:y
    ]


!

buttonMultiPress:button x:x y:y

    (self indicatiorLineForButton:button atX:x y:y) == 0 ifTrue:[
        ^ super buttonMultiPress:button x:x y:y
    ].
    "/ discard doubleClick on indicator
!

buttonPress:button x:x y:y
    "check for indicator
    "
    |expand node lineNr|

    lineNr := self indicatiorLineForButton:button atX:x y:y.

    lineNr == 0 ifTrue:[
        ^ super buttonPress:button x:x y:y
    ].
    node := listOfNodes at:lineNr.

    (     validateDoubleClickBlock isNil
     or:[(validateDoubleClickBlock value:node) ~~ false]
    ) ifFalse:[
        ^ super buttonPress:button x:x y:y
    ].
    discardMotionEvents := true.
    dragIsActive  := false.
    clickPosition := nil.

    self hasSelection ifTrue:[
        (selectConditionBlock isNil or:[selectConditionBlock value:lineNr]) ifTrue:[
            self selection:lineNr
        ] ifFalse:[
            self selection:nil
        ]
    ].
    self nodeAt:lineNr expand:(node isExpandable).

!

buttonRelease:button x:x y:y
    "stop any autoscroll"

    discardMotionEvents ifTrue:[
        clickPosition := nil.
        discardMotionEvents := false.
    ].
    super buttonRelease:button x:x y:y

!

doubleClicked
    "handle a double click; collapse or expand selected entry
     in case of having children
    "
    |node|

    (node := self selectedNode) notNil ifTrue:[
        (     validateDoubleClickBlock isNil
         or:[(validateDoubleClickBlock value:node) ~~ false]
        ) ifTrue:[
            self selectedNodeExpand:(node isExpandable).
            super doubleClicked
        ]
    ]

!

indicatiorLineForButton:aButton atX:x y:y
    "returns linenumber assigned to indicator at x/y or 0
    "
    |sensor nr x0 node|

    (     enabled
     and:[showDirectoryIndicator
     and:[aButton == 1 or:[aButton == #select]]]
    ) ifTrue:[
        sensor := self sensor.

        (sensor ctrlDown or:[sensor shiftDown]) ifFalse:[
            nr := self visibleLineToListLine:(self visibleLineOfY:y).

            nr notNil ifTrue:[
                node := listOfNodes at:nr.
                x0   := self xOfFigureLevel:(node level - 1).

                (x > x0 and:[(x0 + imageWidth) > x and:[node numberOfChildren ~~ 0]]) ifTrue:[
                    ^ nr
                ]
            ]
        ]
    ].            
    ^ 0
!

key:key select:index x:x y:y
    "select an entry by a keyboard action. This is treated like a doubleClick
     on that entry.
     Add on: In case that the entry is not selectable, scroll to the entry
    "
    (enabled and:[keyActionStyle notNil]) ifFalse:[
        ^ self
    ].

    (selectConditionBlock isNil or:[selectConditionBlock value:index]) ifTrue:[
        super key:key select:index x:x y:y
    ].

    keyActionStyle == #pass ifTrue:[
        ^ self
    ].

    self gotoLine:index
! !

!SelectionInTreeView methodsFor:'initialization'!

create
    super create.
    lineMask := lineMask onDevice:device.

    lineColor notNil ifTrue:[
        lineColor := lineColor onDevice:device
    ]
!

destroy
    "remove dependencies
    "
    rootHolder notNil ifTrue:[
        rootHolder removeDependent:self
    ].
    selectionHolder notNil ifTrue:[
        selectionHolder removeDependent:self
    ].
    super destroy.


!

fetchDeviceResources
    "initialize heavily used device resources - to avoid rendering
     images again and again later"

    super fetchDeviceResources.
    self refetchDeviceResources
!

fetchImageResources
    "initialize heavily used device resources - to avoid rendering
     images again and again later; returns maximum extent of the images used.
     Could be redefined by subclass
    "
    |icon extent|

    imageOpened isNil ifTrue:[
        imageOpened := (self class imageOpened) onDevice:device
    ].

    imageClosed isNil ifTrue:[
        imageClosed := self imageOnDevice:(self class imageClosed)
    ].
    extent := (imageOpened extent) max:(imageClosed extent).

    imageItem isNil ifTrue:[
        imageItem := self imageOnDevice:(self class imageItem)
    ].

    (listOfNodes size > 0 and: [(icon := listOfNodes first icon) isImage]) ifTrue: [^icon extent].

    ^ extent max:(imageItem extent)

!

getFontParameters
    "save old computed height derived from images
    "
    |lineHeight|

    lineHeight := fontHeight ? 0.
    super getFontParameters.
    labelOffsetY := fontAscent - (fontHeight - lineSpacing // 2).

    lineHeight > fontHeight ifTrue:[
        fontHeight := lineHeight
    ].
    fontHeight odd ifTrue:[
        fontHeight := fontHeight + 1
    ]
!

initialize
    "setup instance attributes
    "
    super initialize.
    self bitGravity:#NorthWest.
    showRoot := showDirectoryIndicatorForRoot      := showLines := computeResources := true.
    showDirectoryIndicator := discardMotionEvents := false.
    lineMask := Form width:2 height:2 fromArray:#[16rAA 16r55].
    registeredImages := IdentityDictionary new.
    textInset  := 4.
    imageInset := 0.    "/ set during indication enabled
    imageWidth := 8.    "/ default: will change during startup
    self model:nil.     "/ creates a default model.
!

realize
    super realize.
    self  refetchDeviceResources.

!

refetchDeviceResources
    "reinitialize heavily used device resources - to avoid rendering
     images again and again later
    "
    |extent|

    (realized and:[computeResources and:[listOfNodes size ~~ 0]]) ifTrue:[
        computeResources := false.
        extent := self fetchImageResources.

        extent y >= fontHeight ifTrue:[
            fontHeight := 1 + extent y.
        ].
        fontHeight odd ifTrue:[
            fontHeight := fontHeight + 1
        ].

        imageWidth := extent x.
        self recomputeDirectoryIndicator.
        self computeNumberOfLinesShown.
    ]
! !

!SelectionInTreeView methodsFor:'model'!

getListFromModel
    "if I have a model, get my list from it using the listMessage.
     If listMessage is nil, try aspectMessage for backward compatibilty.
    "
    super list:(self listFromModel) keepSelection:true
!

listFromModel
    "get list from model and return the new list.
     If listMessage is nil, try aspectMessage for backward compatibilty.
    "
    |msg|

    widthOfWidestLine := nil.

    (msg := listMsg ? aspectMsg) notNil ifTrue:[
        listOfNodes := model perform:msg.
        listOfNodes size ~~ 0 ifTrue:[
            self refetchDeviceResources.
            ^ listOfNodes collect:[:n|n name]
        ]
    ].
    listOfNodes := #().
  ^ #()
!

model:aModel
    "check whether model is nil; than a default model is created
    "
    |model|

    model := aModel ? (SelectionInTree new).
    model showRoot:showRoot.
    super model:model.
!

rootFromModel
    "update hierarchical list from root model; 'rootHolder'
    "
    |root|

    root := rootHolder root.

    self root == root ifFalse:[
        self selection:nil.
        self root:root.
    ].
!

selectionFromModel
    "set the selection derived from the selectionHolder
    "
    |coll value sz|

    (value := selectionHolder value) isNil ifTrue:[
        ^ self deselect
    ].

    multipleSelectOk ifFalse:[
        self selectNode:value
    ] ifTrue:[
        (sz := value size) ~~ 0 ifTrue:[
            coll := OrderedCollection new:sz.

            value do:[:aNode||i|
                (i := self indexOfNode:aNode) notNil ifTrue:[
                    coll add:i
                ]
            ]
        ].
        coll size == 0 ifTrue:[self deselect]
                      ifFalse:[self selection:coll]
    ]
!

selectionToModel
    "write selection to selection holder
    "
    |newSel oldSel|

    oldSel := selectionHolder value.

    multipleSelectOk ifFalse:[
        (newSel := self selectedNode) ~~ oldSel ifTrue:[
            selectionHolder value:newSel
        ]
    ] ifTrue:[
        selection size == 0 ifTrue:[
            oldSel notNil ifTrue:[
                selectionHolder value:nil
            ]
        ] ifFalse:[
            newSel := selection collect:[:i| listOfNodes at:i].

            newSel size ~~ oldSel size ifTrue:[
                selectionHolder value:newSel.
            ] ifFalse:[
                newSel do:[:aNode|
                    (oldSel includes:aNode) ifFalse:[
                        ^ selectionHolder value:newSel
                    ]
                ]
            ]
        ]
    ]
! !

!SelectionInTreeView methodsFor:'private'!

list:aList keepSelection:keepSelection
    "setup new list; keep selection dependent on the boolean state
     keepSelection
    "
    |list|

    list := aList.

    list size == 0 ifTrue:[
        listOfNodes := #()
    ] ifFalse:[
        (list first respondsTo:#hasChildren) ifTrue:[
            listOfNodes := aList.
            self refetchDeviceResources.
            list := listOfNodes collect:[:aNode| aNode name ].
        ]
    ].
    super list:list keepSelection:keepSelection
!

nodeAt:anIndex expand:doExpand
    "expand or collapse the node at an index, anIndex dependent on the boolean state
     of doExpand
    "
    |node|

    node := listOfNodes at:anIndex.

    node hasChildren ifTrue:[
        node isExpandable ifTrue:[
            doExpand ifFalse:[^ self].
            node expand
        ] ifFalse:[
            doExpand ifTrue:[^ self].
            node collapse
        ].

        node numberOfChildren == 0 ifTrue:[
            "/ no children; redraw selected line (image might change)
            self redrawLine:anIndex.
        ] ifFalse:[
            "/ with children; update list and redraw to end.
            model removeDependent:self.
            model recomputeList.
            model addDependent:self.
            list := self listFromModel.
            self redrawFromLine:anIndex.
            self contentsChanged.
        ]
    ]

!

recomputeDirectoryIndicator
    "setup attributes used by directory indicator
    "
    |x1 x2 y|

    imageInset := 0.

    (showDirectoryIndicator and:[computeResources not]) ifFalse:[
        ^ self
    ].
    openIndicator isNil ifTrue:[
        openIndicator  := self imageOnDevice:(self class openIndicator)
    ].
    closeIndicator isNil ifTrue:[
        closeIndicator := self imageOnDevice:(self class closeIndicator)
    ].

    x1 := (openIndicator widthOn:self) // 2.
    y  := openIndicator heightOn:self.
    extentOpenIndicator := Point x:x1 y:(y // 2).
    x2 := (closeIndicator widthOn:self) // 2.
    y  := closeIndicator heightOn:self.
    extentCloseIndicator := Point x:x2 y:(y // 2).

    x2 > x1 ifTrue:[x1 := x2].

    (x1 := x1 + self class minImageInset) > (imageWidth // 2) ifTrue:[
        imageInset := x1 - (imageWidth // 2).
    ].

! !

!SelectionInTreeView methodsFor:'private queries'!

lengthOfLongestLineBetween:firstLine and:lastLine
    "return the length (in characters) of the longest line in a line-range
    "
    |max|

    max := self widthOfContents:firstLine and:lastLine.
  ^ (max // fontWidth) + 1
!

widthOfContents
    "return the width of the contents in pixels
     - used for scrollbar interface"

    list isNil ifTrue:[^ 0].

    (widthOfWidestLine isNil or:[widthOfWidestLine == 0]) ifTrue:[
        widthOfWidestLine := self widthOfContents:1 and:(self size).
    ].
  ^ widthOfWidestLine + (leftMargin * 2)

!

widthOfContents:firstLine and:lastLine
    "return the length (in pixels) of the longest line in a line-range
    "
    |max      "{ Class: SmallInteger }"
     thisLen  "{ Class: SmallInteger }"
     first    "{ Class: SmallInteger }"
     last     "{ Class: SmallInteger }" |

    listOfNodes size == 0 ifTrue:[^ 0].

    last  := listOfNodes size.
    first := firstLine.

    (first > last) ifTrue:[^ 0].

    (lastLine < last) ifTrue:[
        last := lastLine
    ].
    max  := 0.

    listOfNodes from:first to:last do:[:anItem||name|
        thisLen := self xOfStringNode:anItem.

        (name := anItem name) notNil ifTrue:[
            thisLen := thisLen + (name widthOn:self).
        ].
        (thisLen > max) ifTrue:[
            max := thisLen.
        ]
    ].
  ^ max + leftOffset.
!

withoutRedrawAt:anIndex put:aString
    "change a line without redisplay"

    |width|

    width := widthOfWidestLine.
    widthOfWidestLine := nil.

    super withoutRedrawAt:anIndex put:aString.

    (widthOfWidestLine := width) notNil ifTrue:[
        width := self widthOfContents:anIndex and:anIndex.

        width > widthOfWidestLine ifTrue:[
            widthOfWidestLine := width
        ] ifFalse:[
            widthOfWidestLine := nil "/ means: unknown
        ]
    ].


! !

!SelectionInTreeView methodsFor:'queries'!

figureFor:aNode
    "access figure for a node
    "
    |unregisteredImage registeredImage|

    (unregisteredImage := aNode icon) notNil
    ifTrue:
    [
        (registeredImage := registeredImages at: unregisteredImage ifAbsent: nil) isNil
        ifTrue:
        [           
            registeredImage := unregisteredImage on: device. 
            registeredImage clearMaskedPixels.
            registeredImages at: unregisteredImage put: registeredImage
        ].
        ^registeredImage
    ].

    aNode hasChildren ifTrue:[
        aNode isExpandable ifTrue:[ ^ imageClosed ]
                          ifFalse:[ ^ imageOpened ]
    ].
  ^ imageItem
!

indexOfNode:aNode
    "returns index of a node
    "
    ^ listOfNodes findFirst:[:n| n == aNode ]
!

xOfFigureLevel:aLevel
    "origin x where to draw the icon
    "
    |l|

    showRoot ifTrue:[l := aLevel]
            ifFalse:[l := aLevel - 1].

    showDirectoryIndicator ifFalse:[
        l := l - 1
    ] ifTrue:[
        showDirectoryIndicatorForRoot ifFalse:[
            l := l - 1
        ]
    ].
  ^ (l * (imageInset + imageWidth)) + imageInset - leftOffset + leftMargin

!

xOfFigureNode:aNode
    "origin x where to draw the icon
    "
    ^ self xOfFigureLevel:(aNode level)
!

xOfStringLevel:aLevel
    "origin x where to draw the text( label )
    "
    ^ (self xOfFigureLevel:aLevel) + imageWidth + textInset

!

xOfStringNode:aNode
    "origin x where to draw the text( label )
    "
    ^ self xOfStringLevel:(aNode level)

! !

!SelectionInTreeView methodsFor:'selection'!

selectFromListOfNames:aListOfNames
    "set selection from a list of names
    "
    |node rdwNd|

    aListOfNames size < 1 ifTrue:[
        ^ self selection:nil
    ].

    node := model root.

    aListOfNames do:[:el||next|
        next := node detectChild:[:e|e name = el].

        next notNil ifTrue:[
            node hidden ifTrue:[
                rdwNd isNil ifTrue:[
                    rdwNd := node.
                    self selectNode:node.
                ].
                node expand
            ].
            node := next
        ]
    ].

    rdwNd notNil ifTrue:[
        model removeDependent:self.
        model recomputeList.
        model addDependent:self.
        list := self listFromModel.
        self redrawFromLine:(self indexOfNode:rdwNd).
        self contentsChanged.
    ].
    self selectNode:node.

!

selectNode:aNode
    "change selection to a node
    "
    self selection:(self indexOfNode:aNode)


!

selectedIndex
    "get single selected index or 0
    "
    selection size == 1 ifTrue:[^ selection first].
    selection isNumber  ifTrue:[^ selection].
  ^ 0
!

selectedNode
    "get the single selected node or nil
    "
    |idx|

    (idx := self selectedIndex) ~~ 0 ifTrue:[
        ^ listOfNodes at:idx
    ].
  ^ nil
!

selectionChangedFrom:oldSelection
    "update selectionHolder if not nil
    "

    "/ first change my selectionHolders value ...
    selectionHolder notNil ifTrue:[
        self selectionToModel.
    ].

    "/ ... then make notifications.
    super selectionChangedFrom:oldSelection.


! !

!SelectionInTreeView methodsFor:'selection-actions'!

selectedNodeAdd:something
    "add a node or collection of nodes after selected node
    "
    |node|

    something notNil ifTrue:[
        (node := self selectedNode) notNil ifTrue:[
            node parent notNil ifTrue:[
                node isCollapsable ifTrue:[
                    model add:something beforeIndex:1 below:node
                ] ifFalse:[
                    model add:something after:node
                ]
            ] ifFalse:[
                model add:something beforeIndex:1 below:(self root)
            ]
        ]
    ]

!

selectedNodeBecomeChildOfNext
    "become node a child of followd node
    "
    |idx node cprt nprt|

    ((node := self selectedNode) isNil or:[(cprt := node parent) isNil]) ifFalse:[
        idx := cprt indexOfChild:node.

        idx == cprt children size ifFalse:[
            nprt := cprt childAt:(idx + 1).

            nprt notNil ifTrue:[
                model removeDependent:self.
                model removeSelection.
                selection := nil.
                model collapse:nprt.
                model add:node beforeIndex:1 below:nprt.
                model addDependent:self.
                model expand:nprt.

                self selectNode:node.
            ]
        ]
    ]
!

selectedNodeBecomeSisterOfParent
    "become node a sister of its current parent
    "
    |node cprt nprt|

    (    (node := self selectedNode) isNil
     or:[(cprt := node parent) isNil
     or:[(nprt := cprt parent) isNil]]
    ) ifFalse:[
        model removeDependent:self.
        model removeSelection.
        selection := nil.
        model addDependent:self.

        model add:node afterIndex:(nprt indexOfChild:cprt) below:nprt.
        self selectNode:node.
    ]

!

selectedNodeChangeSequenceOrder:anOffset
    "move child 'anOffset' forward or backward in list of children
    "
    |idx node size parent|

    (      (node   := self selectedNode) notNil
      and:[(parent := node parent) notNil
      and:[(size   := parent children size) > 1]]
    ) ifTrue:[
        idx := parent indexOfChild:node.

        model removeDependent:self.
        model removeSelection.
        selection := nil.
        model addDependent:self.

        (idx := idx + anOffset) < 1 ifTrue:[
            idx := size
        ] ifFalse:[
            idx > size ifTrue:[idx := 1]
        ].
        model add:node beforeIndex:idx below:parent.
        self selectNode:node.
    ]
!

selectedNodeExpand:doExpand
    "collapse or expand selected node
    "
    |node index|

    (index := self selectedIndex) ~~ 0 ifTrue:[
        node := listOfNodes at:index.

        node hasChildren ifTrue:[
            node isExpandable ifTrue:[
                doExpand ifFalse:[^ self].
                node expand
            ] ifFalse:[
                doExpand ifTrue:[^ self].
                node collapse
            ].

            node numberOfChildren == 0 ifTrue:[
                "/ no children; redraw selected line (image might change)
                self redrawLine:index.
            ] ifFalse:[
                "/ with children; update list and redraw to end.
                model removeDependent:self.
                model recomputeList.
                model addDependent:self.
                list := self listFromModel.
                self redrawFromLine:index.
                self contentsChanged.
            ]
        ]
    ].
!

selectedNodesRemove
    "remove selected nodes
    "
    model removeSelection.
    self selection:nil.

! !

!SelectionInTreeView class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libwidg2/SelectionInTreeView.st,v 1.43 1998-02-22 13:36:02 tz Exp $'
! !