| 1 |
package fzf |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"maps" |
| 10 |
"math" |
| 11 |
"net" |
| 12 |
"os" |
| 13 |
"os/exec" |
| 14 |
"os/signal" |
| 15 |
"regexp" |
| 16 |
"slices" |
| 17 |
"sort" |
| 18 |
"strconv" |
| 19 |
"strings" |
| 20 |
"sync" |
| 21 |
"sync/atomic" |
| 22 |
"syscall" |
| 23 |
"time" |
| 24 |
"unicode" |
| 25 |
|
| 26 |
"github.com/rivo/uniseg" |
| 27 |
|
| 28 |
"github.com/junegunn/fzf/src/tui" |
| 29 |
"github.com/junegunn/fzf/src/util" |
| 30 |
) |
| 31 |
|
| 32 |
// import "github.com/pkg/profile" |
| 33 |
|
| 34 |
/* |
| 35 |
Placeholder regex is used to extract placeholders from fzf's template |
| 36 |
strings. Acts as input validation for parsePlaceholder function. |
| 37 |
Describes the syntax, but it is fairly lenient. |
| 38 |
|
| 39 |
The following pseudo regex has been reverse engineered from the |
| 40 |
implementation. It is overly strict, but better describes what's possible. |
| 41 |
As such it is not useful for validation, but rather to generate test |
| 42 |
cases for example. |
| 43 |
|
| 44 |
\\?(?: # escaped type |
| 45 |
{\+?s?f?r?RANGE(?:,RANGE)*} # token type |
| 46 |
{q[:s?RANGE]} # query type |
| 47 |
|{\+?n?f?} # item type (notice no mandatory element inside brackets) |
| 48 |
) |
| 49 |
RANGE = (?: |
| 50 |
(?:-?[0-9]+)?\.\.(?:-?[0-9]+)? # ellipsis syntax for token range (x..y) |
| 51 |
|-?[0-9]+ # shorthand syntax (x..x) |
| 52 |
) |
| 53 |
*/ |
| 54 |
var placeholder *regexp.Regexp |
| 55 |
var whiteSuffix *regexp.Regexp |
| 56 |
var offsetComponentRegex *regexp.Regexp |
| 57 |
var offsetTrimCharsRegex *regexp.Regexp |
| 58 |
var passThroughBeginRegex *regexp.Regexp |
| 59 |
var passThroughEndTmuxRegex *regexp.Regexp |
| 60 |
var sixelBeginRegex *regexp.Regexp |
| 61 |
var cursorBackRegex *regexp.Regexp |
| 62 |
var ttyin *os.File |
| 63 |
|
| 64 |
var inTmux = len(os.Getenv("TMUX")) > 0 |
| 65 |
|
| 66 |
const clearCode string = "\x1b[2J" |
| 67 |
|
| 68 |
// Number of maximum focus events to process synchronously |
| 69 |
const maxFocusEvents = 10000 |
| 70 |
|
| 71 |
// execute-silent and transform* actions will block user input for this duration. |
| 72 |
// After this duration, users can press CTRL-C to terminate the command. |
| 73 |
const blockDuration = 1 * time.Second |
| 74 |
|
| 75 |
// Skip exporting FZF_CURRENT_ITEM when the item is larger than this, so a huge |
| 76 |
// item cannot overflow ARG_MAX and break exec for preview and other commands. |
| 77 |
const maxCurrentItemEnvSize = 64 * 1024 |
| 78 |
|
| 79 |
func init() { |
| 80 |
placeholder = regexp.MustCompile(`\\?(?:{[+*sfr]*[0-9,-.]*}|{q(?::s?[0-9,-.]+)?}|{fzf:(?:query|action|prompt)}|{[+*]?f?nf?})`) |
| 81 |
whiteSuffix = regexp.MustCompile(`\s*$`) |
| 82 |
offsetComponentRegex = regexp.MustCompile(`([+-][0-9]+)|(-?/[1-9][0-9]*)`) |
| 83 |
offsetTrimCharsRegex = regexp.MustCompile(`[^0-9/+-]`) |
| 84 |
|
| 85 |
// Parts of the preview output that should be passed through to the terminal |
| 86 |
// * https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it |
| 87 |
// * https://sw.kovidgoyal.net/kitty/graphics-protocol |
| 88 |
// * https://en.wikipedia.org/wiki/Sixel |
| 89 |
// * https://iterm2.com/documentation-images.html |
| 90 |
/* |
| 91 |
passThroughRegex = regexp.MustCompile(` |
| 92 |
\x1bPtmux;\x1b\x1b .*? [^\x1b]\x1b\\ |
| 93 |
| \x1b(_G|P[0-9;]*q) .*? \x1b\\\r? |
| 94 |
| \x1b]1337; .*? (\a|\x1b\\) |
| 95 |
`) |
| 96 |
*/ |
| 97 |
passThroughBeginRegex = regexp.MustCompile(`\x1bPtmux;\x1b\x1b|\x1b(_G|P[0-9;]*q)|\x1b]1337;`) |
| 98 |
passThroughEndTmuxRegex = regexp.MustCompile(`[^\x1b]\x1b\\`) |
| 99 |
sixelBeginRegex = regexp.MustCompile(`^\x1bP[0-9;]*q`) |
| 100 |
|
| 101 |
// CUB right before an IND, used to return to the column a row started on |
| 102 |
cursorBackRegex = regexp.MustCompile(`\x1b\[([0-9]*)D$`) |
| 103 |
} |
| 104 |
|
| 105 |
type jumpMode int |
| 106 |
|
| 107 |
const ( |
| 108 |
jumpDisabled jumpMode = iota |
| 109 |
jumpEnabled |
| 110 |
jumpAcceptEnabled |
| 111 |
) |
| 112 |
|
| 113 |
type resumableState int |
| 114 |
|
| 115 |
const ( |
| 116 |
disabledState resumableState = iota |
| 117 |
pausedState |
| 118 |
enabledState |
| 119 |
) |
| 120 |
|
| 121 |
func (s resumableState) Enabled() bool { |
| 122 |
return s == enabledState |
| 123 |
} |
| 124 |
|
| 125 |
func (s *resumableState) Force(flag bool) { |
| 126 |
if flag { |
| 127 |
*s = enabledState |
| 128 |
} else { |
| 129 |
*s = disabledState |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
func (s *resumableState) Set(flag bool) { |
| 134 |
if *s == disabledState { |
| 135 |
return |
| 136 |
} |
| 137 |
|
| 138 |
if flag { |
| 139 |
*s = enabledState |
| 140 |
} else { |
| 141 |
*s = pausedState |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
type commandSpec struct { |
| 146 |
command string |
| 147 |
tempFiles []string |
| 148 |
} |
| 149 |
|
| 150 |
type quitSignal struct { |
| 151 |
code int |
| 152 |
err error |
| 153 |
} |
| 154 |
|
| 155 |
type waitState struct { |
| 156 |
blocked bool |
| 157 |
blockedAt time.Time |
| 158 |
pending []*action |
| 159 |
searching bool // a search is in progress or the input is still loading |
| 160 |
} |
| 161 |
|
| 162 |
type previewer struct { |
| 163 |
version int64 |
| 164 |
lines []string |
| 165 |
offset int |
| 166 |
scrollable bool |
| 167 |
final bool |
| 168 |
following resumableState |
| 169 |
spinner string |
| 170 |
bar []bool |
| 171 |
xw [2]int |
| 172 |
} |
| 173 |
|
| 174 |
type previewed struct { |
| 175 |
version int64 |
| 176 |
numLines int |
| 177 |
offset int |
| 178 |
filled bool |
| 179 |
image bool |
| 180 |
wipe bool |
| 181 |
wireframe bool |
| 182 |
} |
| 183 |
|
| 184 |
type eachLine struct { |
| 185 |
line string |
| 186 |
err error |
| 187 |
} |
| 188 |
|
| 189 |
type itemLine struct { |
| 190 |
valid bool |
| 191 |
firstLine int |
| 192 |
numLines int |
| 193 |
cy int |
| 194 |
current bool |
| 195 |
selected bool |
| 196 |
label string |
| 197 |
queryLen int |
| 198 |
width int |
| 199 |
hasBar bool |
| 200 |
result Result |
| 201 |
empty bool |
| 202 |
other bool |
| 203 |
hidden bool |
| 204 |
} |
| 205 |
|
| 206 |
func (t *Terminal) inListWindow() bool { |
| 207 |
return t.window != t.inputWindow && t.window != t.headerWindow && t.window != t.headerLinesWindow && t.window != t.footerWindow |
| 208 |
} |
| 209 |
|
| 210 |
func (t *Terminal) markEmptyLine(line int) { |
| 211 |
if t.inListWindow() { |
| 212 |
t.prevLines[line] = itemLine{valid: true, firstLine: line, empty: true} |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
func (t *Terminal) markOtherLine(line int) { |
| 217 |
if t.inListWindow() { |
| 218 |
t.prevLines[line] = itemLine{valid: true, firstLine: line, other: true} |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
type fitpad struct { |
| 223 |
fit int |
| 224 |
pad int |
| 225 |
} |
| 226 |
|
| 227 |
type labelPrinter func(tui.Window, int) |
| 228 |
|
| 229 |
type markerClass int |
| 230 |
|
| 231 |
const ( |
| 232 |
markerSingle markerClass = iota |
| 233 |
markerTop |
| 234 |
markerMiddle |
| 235 |
markerBottom |
| 236 |
) |
| 237 |
|
| 238 |
type StatusItem struct { |
| 239 |
Index int `json:"index"` |
| 240 |
Text string `json:"text"` |
| 241 |
Positions []int `json:"positions,omitempty"` |
| 242 |
} |
| 243 |
|
| 244 |
type Status struct { |
| 245 |
Reading bool `json:"reading"` |
| 246 |
Progress int `json:"progress"` |
| 247 |
Query string `json:"query"` |
| 248 |
Position int `json:"position"` |
| 249 |
Sort bool `json:"sort"` |
| 250 |
TotalCount int `json:"totalCount"` |
| 251 |
MatchCount int `json:"matchCount"` |
| 252 |
Current *StatusItem `json:"current"` |
| 253 |
Matches []StatusItem `json:"matches"` |
| 254 |
Selected []StatusItem `json:"selected"` |
| 255 |
} |
| 256 |
|
| 257 |
type versionedCallback struct { |
| 258 |
version int64 |
| 259 |
callback func() |
| 260 |
} |
| 261 |
|
| 262 |
type runningCmd struct { |
| 263 |
cmd *exec.Cmd |
| 264 |
tempFiles []string |
| 265 |
} |
| 266 |
|
| 267 |
// Terminal represents terminal input/output |
| 268 |
type Terminal struct { |
| 269 |
initDelay time.Duration |
| 270 |
infoCommand string |
| 271 |
infoStyle infoStyle |
| 272 |
infoPrefix string |
| 273 |
wrap bool |
| 274 |
wrapWord bool |
| 275 |
wrapSign string |
| 276 |
wrapSignWidth int |
| 277 |
previewWrapSign string |
| 278 |
previewWrapSignWidth int |
| 279 |
ghost string |
| 280 |
separator labelPrinter |
| 281 |
separatorLen int |
| 282 |
separatorAuto bool |
| 283 |
spinner []string |
| 284 |
promptString string |
| 285 |
prompt func() |
| 286 |
promptLen int |
| 287 |
borderLabel labelPrinter |
| 288 |
borderLabelLen int |
| 289 |
borderLabelOpts labelOpts |
| 290 |
previewLabel labelPrinter |
| 291 |
previewLabelLen int |
| 292 |
previewLabelOpts labelOpts |
| 293 |
inputLabel labelPrinter |
| 294 |
inputLabelLen int |
| 295 |
inputLabelOpts labelOpts |
| 296 |
headerLabel labelPrinter |
| 297 |
headerLabelLen int |
| 298 |
headerLabelOpts labelOpts |
| 299 |
footerLabel labelPrinter |
| 300 |
footerLabelLen int |
| 301 |
footerLabelOpts labelOpts |
| 302 |
gutterReverse bool |
| 303 |
gutterRawReverse bool |
| 304 |
pointer string |
| 305 |
pointerLen int |
| 306 |
pointerEmpty string |
| 307 |
pointerEmptyRaw string |
| 308 |
marker string |
| 309 |
markerLen int |
| 310 |
markerEmpty string |
| 311 |
markerMultiLine [3]string |
| 312 |
queryLen [2]int |
| 313 |
layout layoutType |
| 314 |
fullscreen bool |
| 315 |
keepRight bool |
| 316 |
hscroll bool |
| 317 |
hscrollOff int |
| 318 |
scrollOff int |
| 319 |
gap int |
| 320 |
gapLine labelPrinter |
| 321 |
gapLineLen int |
| 322 |
wordRubout string |
| 323 |
wordNext string |
| 324 |
subWordRubout string |
| 325 |
subWordNext string |
| 326 |
cx int |
| 327 |
cy int |
| 328 |
offset int |
| 329 |
xoffset int |
| 330 |
yanked []rune |
| 331 |
input []rune |
| 332 |
inputOverride *[]rune |
| 333 |
pasting *[]rune |
| 334 |
multi int |
| 335 |
multiLine bool |
| 336 |
sort bool |
| 337 |
toggleSort bool |
| 338 |
track trackOption |
| 339 |
idNth []Range |
| 340 |
trackKey string |
| 341 |
trackBlocked bool |
| 342 |
trackSync bool |
| 343 |
trackKeyCache map[int32]bool |
| 344 |
wait waitState |
| 345 |
pendingSelections map[string]selectedItem |
| 346 |
targetIndex int32 |
| 347 |
delimiter Delimiter |
| 348 |
expect map[tui.Event]string |
| 349 |
keymap map[tui.Event][]*action |
| 350 |
keymapOrg map[tui.Event][]*action |
| 351 |
pressed string |
| 352 |
printQueue []string |
| 353 |
printQuery bool |
| 354 |
history *History |
| 355 |
cycle bool |
| 356 |
highlightLine bool |
| 357 |
headerVisible bool |
| 358 |
headerFirst bool |
| 359 |
headerLines int |
| 360 |
header []Item |
| 361 |
header0 []string |
| 362 |
footer []string |
| 363 |
ellipsis string |
| 364 |
scrollbar string |
| 365 |
previewScrollbar string |
| 366 |
ansi bool |
| 367 |
freezeLeft int |
| 368 |
freezeRight int |
| 369 |
nthAttr tui.Attr |
| 370 |
nth []Range |
| 371 |
nthCurrent []Range |
| 372 |
withNthDefault string |
| 373 |
withNthExpr string |
| 374 |
withNthEnabled bool |
| 375 |
acceptNth func([]Token, int32) string |
| 376 |
tabstop int |
| 377 |
margin [4]sizeSpec |
| 378 |
padding [4]sizeSpec |
| 379 |
unicode bool |
| 380 |
listenAddr *listenAddress |
| 381 |
listenPort *int |
| 382 |
listener net.Listener |
| 383 |
listenUnsafe bool |
| 384 |
borderShape tui.BorderShape |
| 385 |
listBorderShape tui.BorderShape |
| 386 |
inputBorderShape tui.BorderShape |
| 387 |
headerBorderShape tui.BorderShape |
| 388 |
headerLinesShape tui.BorderShape |
| 389 |
footerBorderShape tui.BorderShape |
| 390 |
listLabel labelPrinter |
| 391 |
listLabelLen int |
| 392 |
listLabelOpts labelOpts |
| 393 |
cleanExit bool |
| 394 |
executor *util.Executor |
| 395 |
paused bool |
| 396 |
inputless bool |
| 397 |
border tui.Window |
| 398 |
window tui.Window |
| 399 |
inputWindow tui.Window |
| 400 |
inputBorder tui.Window |
| 401 |
headerWindow tui.Window |
| 402 |
headerBorder tui.Window |
| 403 |
headerLinesWindow tui.Window |
| 404 |
headerLinesBorder tui.Window |
| 405 |
footerWindow tui.Window |
| 406 |
footerBorder tui.Window |
| 407 |
wborder tui.Window |
| 408 |
pborder tui.Window |
| 409 |
pwindow tui.Window |
| 410 |
borderWidth int |
| 411 |
count int |
| 412 |
progress int |
| 413 |
hasStartActions bool |
| 414 |
hasResultActions bool |
| 415 |
hasFocusActions bool |
| 416 |
hasLoadActions bool |
| 417 |
hasResizeActions bool |
| 418 |
triggerLoad bool |
| 419 |
pendingReqList bool |
| 420 |
filterSelection bool |
| 421 |
reading bool |
| 422 |
running *util.AtomicBool |
| 423 |
failed *string |
| 424 |
jumping jumpMode |
| 425 |
jumpLabels string |
| 426 |
printer func(string) |
| 427 |
printsep string |
| 428 |
merger *Merger |
| 429 |
passMerger *Merger |
| 430 |
resultMerger *Merger |
| 431 |
matchMap map[int32]Result |
| 432 |
selected map[int32]selectedItem |
| 433 |
version int64 |
| 434 |
revision revision |
| 435 |
bgVersion int64 |
| 436 |
runningCmds *util.ConcurrentSet[*runningCmd] |
| 437 |
reqBox *util.EventBox |
| 438 |
initialPreviewOpts previewOpts |
| 439 |
previewOpts previewOpts |
| 440 |
activePreviewOpts *previewOpts |
| 441 |
previewer previewer |
| 442 |
previewed previewed |
| 443 |
previewBox *util.EventBox |
| 444 |
eventBox *util.EventBox |
| 445 |
mutex sync.Mutex |
| 446 |
uiMutex sync.Mutex |
| 447 |
initFunc func() error |
| 448 |
prevLines []itemLine |
| 449 |
suppress bool |
| 450 |
startChan chan fitpad |
| 451 |
killChan chan bool |
| 452 |
killedChan chan bool |
| 453 |
serverInputChan chan []*action |
| 454 |
callbackChan chan versionedCallback |
| 455 |
bgQueue map[action][]func(bool) |
| 456 |
bgSemaphore chan struct{} |
| 457 |
bgSemaphores map[action]chan struct{} |
| 458 |
keyChan chan tui.Event |
| 459 |
eventChan chan tui.Event |
| 460 |
timerChan chan tui.Event |
| 461 |
slab *util.Slab |
| 462 |
theme *tui.ColorTheme |
| 463 |
tui tui.Renderer |
| 464 |
ttyDefault string |
| 465 |
ttyin *os.File |
| 466 |
executing *util.AtomicBool |
| 467 |
termSize tui.TermSize |
| 468 |
lastAction actionType |
| 469 |
lastKey string |
| 470 |
lastFocus int32 |
| 471 |
areaLines int |
| 472 |
areaColumns int |
| 473 |
forcePreview bool |
| 474 |
clickHeaderLine int |
| 475 |
clickHeaderColumn int |
| 476 |
clickFooterLine int |
| 477 |
clickFooterColumn int |
| 478 |
proxyScript string |
| 479 |
setNativeLabel func(string) |
| 480 |
numLinesCache map[int32]numLinesCacheValue |
| 481 |
raw bool |
| 482 |
lastActivity time.Time |
| 483 |
} |
| 484 |
|
| 485 |
type numLinesCacheValue struct { |
| 486 |
atMost int |
| 487 |
numLines int |
| 488 |
} |
| 489 |
|
| 490 |
type selectedItem struct { |
| 491 |
at time.Time |
| 492 |
item *Item |
| 493 |
} |
| 494 |
|
| 495 |
type byTimeOrder []selectedItem |
| 496 |
|
| 497 |
func (a byTimeOrder) Len() int { |
| 498 |
return len(a) |
| 499 |
} |
| 500 |
|
| 501 |
func (a byTimeOrder) Swap(i, j int) { |
| 502 |
a[i], a[j] = a[j], a[i] |
| 503 |
} |
| 504 |
|
| 505 |
func (a byTimeOrder) Less(i, j int) bool { |
| 506 |
return a[i].at.Before(a[j].at) |
| 507 |
} |
| 508 |
|
| 509 |
// EventTypes are listed in the order of their priority. |
| 510 |
const ( |
| 511 |
reqResize util.EventType = iota |
| 512 |
reqReinit |
| 513 |
reqFullRedraw |
| 514 |
reqRedraw |
| 515 |
|
| 516 |
reqJump |
| 517 |
reqPrompt |
| 518 |
reqInfo |
| 519 |
reqHeader |
| 520 |
reqFooter |
| 521 |
reqList |
| 522 |
reqRedrawInputLabel |
| 523 |
reqRedrawHeaderLabel |
| 524 |
reqRedrawFooterLabel |
| 525 |
reqRedrawListLabel |
| 526 |
reqRedrawBorderLabel |
| 527 |
reqRedrawPreviewLabel |
| 528 |
|
| 529 |
reqPreviewReady |
| 530 |
reqPreviewEnqueue |
| 531 |
reqPreviewDisplay |
| 532 |
reqPreviewRefresh |
| 533 |
reqPreviewDelayed |
| 534 |
|
| 535 |
reqActivate |
| 536 |
reqClose |
| 537 |
reqPrintQuery |
| 538 |
reqBecome |
| 539 |
reqQuit |
| 540 |
reqFatal |
| 541 |
) |
| 542 |
|
| 543 |
func isTerminalEvent(et util.EventType) bool { |
| 544 |
switch et { |
| 545 |
case reqClose, reqPrintQuery, reqBecome, reqQuit, reqFatal: |
| 546 |
return true |
| 547 |
} |
| 548 |
return false |
| 549 |
} |
| 550 |
|
| 551 |
type action struct { |
| 552 |
t actionType |
| 553 |
a string |
| 554 |
} |
| 555 |
|
| 556 |
//go:generate stringer -type=actionType |
| 557 |
type actionType int |
| 558 |
|
| 559 |
const ( |
| 560 |
actIgnore actionType = iota |
| 561 |
actStart |
| 562 |
actClick |
| 563 |
actInvalid |
| 564 |
actBracketedPasteBegin |
| 565 |
actBracketedPasteEnd |
| 566 |
actChar |
| 567 |
actMouse |
| 568 |
actBeginningOfLine |
| 569 |
actAbort |
| 570 |
actAccept |
| 571 |
actAcceptNonEmpty |
| 572 |
actAcceptOrPrintQuery |
| 573 |
actBackwardChar |
| 574 |
actBackwardDeleteChar |
| 575 |
actBackwardDeleteCharEof |
| 576 |
actBackwardWord |
| 577 |
actBackwardSubWord |
| 578 |
actCancel |
| 579 |
|
| 580 |
actChangeBorderLabel |
| 581 |
actChangeGhost |
| 582 |
actChangeHeader |
| 583 |
actChangeHeaderLines |
| 584 |
actChangeFooter |
| 585 |
actChangeHeaderLabel |
| 586 |
actChangeFooterLabel |
| 587 |
actChangeInputLabel |
| 588 |
actChangeListLabel |
| 589 |
actChangeMulti |
| 590 |
actChangeNth |
| 591 |
actChangeWithNth |
| 592 |
actChangePointer |
| 593 |
actChangePreview |
| 594 |
actChangePreviewLabel |
| 595 |
actChangePreviewWindow |
| 596 |
actChangePrompt |
| 597 |
actChangeQuery |
| 598 |
|
| 599 |
actClearScreen |
| 600 |
actClearQuery |
| 601 |
actClearSelection |
| 602 |
actClose |
| 603 |
actDeleteChar |
| 604 |
actDeleteCharEof |
| 605 |
actEndOfLine |
| 606 |
actFatal |
| 607 |
actForwardChar |
| 608 |
actForwardWord |
| 609 |
actForwardSubWord |
| 610 |
actKillLine |
| 611 |
actKillWord |
| 612 |
actKillSubWord |
| 613 |
actUnixLineDiscard |
| 614 |
actUnixWordRubout |
| 615 |
actYank |
| 616 |
actBackwardKillWord |
| 617 |
actBackwardKillSubWord |
| 618 |
actSelectAll |
| 619 |
actDeselectAll |
| 620 |
actToggle |
| 621 |
actToggleSearch |
| 622 |
actToggleAll |
| 623 |
actToggleDown |
| 624 |
actToggleUp |
| 625 |
actToggleIn |
| 626 |
actToggleOut |
| 627 |
actToggleTrack |
| 628 |
actToggleTrackCurrent |
| 629 |
actToggleHeader |
| 630 |
actToggleWrap |
| 631 |
actToggleWrapWord |
| 632 |
actToggleMultiLine |
| 633 |
actToggleHscroll |
| 634 |
actToggleRaw |
| 635 |
actEnableRaw |
| 636 |
actDisableRaw |
| 637 |
actTrackCurrent |
| 638 |
actToggleInput |
| 639 |
actHideInput |
| 640 |
actShowInput |
| 641 |
actUntrackCurrent |
| 642 |
actDown |
| 643 |
actDownMatch |
| 644 |
actUp |
| 645 |
actUpMatch |
| 646 |
actPageUp |
| 647 |
actPageDown |
| 648 |
actPosition |
| 649 |
actHalfPageUp |
| 650 |
actHalfPageDown |
| 651 |
actOffsetUp |
| 652 |
actOffsetDown |
| 653 |
actOffsetMiddle |
| 654 |
actJump |
| 655 |
actJumpAccept // XXX Deprecated in favor of jump:accept binding |
| 656 |
actPrintQuery // XXX Deprecated (not very useful, just use --print-query) |
| 657 |
actRefreshPreview |
| 658 |
actReplaceQuery |
| 659 |
actToggleSort |
| 660 |
actShowPreview |
| 661 |
actHidePreview |
| 662 |
actTogglePreview |
| 663 |
actTogglePreviewWrap |
| 664 |
actTogglePreviewWrapWord |
| 665 |
|
| 666 |
actTransform |
| 667 |
actTransformBorderLabel |
| 668 |
actTransformGhost |
| 669 |
actTransformHeader |
| 670 |
actTransformHeaderLines |
| 671 |
actTransformFooter |
| 672 |
actTransformHeaderLabel |
| 673 |
actTransformFooterLabel |
| 674 |
actTransformInputLabel |
| 675 |
actTransformListLabel |
| 676 |
actTransformNth |
| 677 |
actTransformWithNth |
| 678 |
actTransformPointer |
| 679 |
actTransformPreviewLabel |
| 680 |
actTransformPrompt |
| 681 |
actTransformQuery |
| 682 |
actTransformSearch |
| 683 |
|
| 684 |
actTrigger |
| 685 |
|
| 686 |
actBgTransform |
| 687 |
actBgTransformBorderLabel |
| 688 |
actBgTransformGhost |
| 689 |
actBgTransformHeader |
| 690 |
actBgTransformHeaderLines |
| 691 |
actBgTransformFooter |
| 692 |
actBgTransformHeaderLabel |
| 693 |
actBgTransformFooterLabel |
| 694 |
actBgTransformInputLabel |
| 695 |
actBgTransformListLabel |
| 696 |
actBgTransformNth |
| 697 |
actBgTransformWithNth |
| 698 |
actBgTransformPointer |
| 699 |
actBgTransformPreviewLabel |
| 700 |
actBgTransformPrompt |
| 701 |
actBgTransformQuery |
| 702 |
actBgTransformSearch |
| 703 |
|
| 704 |
actBgCancel |
| 705 |
|
| 706 |
actSearch |
| 707 |
actPreview |
| 708 |
actPreviewTop |
| 709 |
actPreviewBottom |
| 710 |
actPreviewUp |
| 711 |
actPreviewDown |
| 712 |
actPreviewPageUp |
| 713 |
actPreviewPageDown |
| 714 |
actPreviewHalfPageUp |
| 715 |
actPreviewHalfPageDown |
| 716 |
actPrevHistory |
| 717 |
actPrevSelected |
| 718 |
actPrint |
| 719 |
actPut |
| 720 |
actNextHistory |
| 721 |
actNextSelected |
| 722 |
actExecute |
| 723 |
actExecuteSilent |
| 724 |
actExecuteMulti // Deprecated |
| 725 |
actSigStop |
| 726 |
actBest |
| 727 |
actFirst |
| 728 |
actLast |
| 729 |
actReload |
| 730 |
actReloadSync |
| 731 |
actDisableSearch |
| 732 |
actEnableSearch |
| 733 |
actSelect |
| 734 |
actDeselect |
| 735 |
actUnbind |
| 736 |
actRebind |
| 737 |
actToggleBind |
| 738 |
actBecome |
| 739 |
actShowHeader |
| 740 |
actHideHeader |
| 741 |
actBell |
| 742 |
actExclude |
| 743 |
actExcludeMulti |
| 744 |
actAsync |
| 745 |
actWait |
| 746 |
) |
| 747 |
|
| 748 |
func (a actionType) Name() string { |
| 749 |
return util.ToKebabCase(a.String()[3:]) |
| 750 |
} |
| 751 |
|
| 752 |
func processExecution(action actionType) bool { |
| 753 |
switch action { |
| 754 |
case actTransform, |
| 755 |
actTransformBorderLabel, |
| 756 |
actTransformGhost, |
| 757 |
actTransformHeader, |
| 758 |
actTransformHeaderLines, |
| 759 |
actTransformFooter, |
| 760 |
actTransformHeaderLabel, |
| 761 |
actTransformFooterLabel, |
| 762 |
actTransformInputLabel, |
| 763 |
actTransformListLabel, |
| 764 |
actTransformNth, |
| 765 |
actTransformWithNth, |
| 766 |
actTransformPointer, |
| 767 |
actTransformPreviewLabel, |
| 768 |
actTransformPrompt, |
| 769 |
actTransformQuery, |
| 770 |
actTransformSearch, |
| 771 |
actBgTransform, |
| 772 |
actBgTransformBorderLabel, |
| 773 |
actBgTransformGhost, |
| 774 |
actBgTransformHeader, |
| 775 |
actBgTransformHeaderLines, |
| 776 |
actBgTransformFooter, |
| 777 |
actBgTransformHeaderLabel, |
| 778 |
actBgTransformFooterLabel, |
| 779 |
actBgTransformInputLabel, |
| 780 |
actBgTransformListLabel, |
| 781 |
actBgTransformNth, |
| 782 |
actBgTransformWithNth, |
| 783 |
actBgTransformPointer, |
| 784 |
actBgTransformPreviewLabel, |
| 785 |
actBgTransformPrompt, |
| 786 |
actBgTransformQuery, |
| 787 |
actBgTransformSearch, |
| 788 |
actPreview, |
| 789 |
actChangePreview, |
| 790 |
actRefreshPreview, |
| 791 |
actExecute, |
| 792 |
actExecuteSilent, |
| 793 |
actExecuteMulti, |
| 794 |
actReload, |
| 795 |
actReloadSync, |
| 796 |
actBecome: |
| 797 |
return true |
| 798 |
} |
| 799 |
return false |
| 800 |
} |
| 801 |
|
| 802 |
type placeholderFlags struct { |
| 803 |
plus bool |
| 804 |
asterisk bool |
| 805 |
preserveSpace bool |
| 806 |
number bool |
| 807 |
forceUpdate bool |
| 808 |
file bool |
| 809 |
raw bool |
| 810 |
} |
| 811 |
|
| 812 |
type withNthSpec struct { |
| 813 |
fn func([]Token, int32) string // nil = clear (restore original) |
| 814 |
} |
| 815 |
|
| 816 |
type searchRequest struct { |
| 817 |
sort bool |
| 818 |
sync bool |
| 819 |
nth *[]Range |
| 820 |
withNth *withNthSpec |
| 821 |
headerLines *int |
| 822 |
command *commandSpec |
| 823 |
environ []string |
| 824 |
changed bool |
| 825 |
denylist []int32 |
| 826 |
revision revision |
| 827 |
} |
| 828 |
|
| 829 |
type previewRequest struct { |
| 830 |
template string |
| 831 |
scrollOffset int |
| 832 |
list [3][]*Item // current, select, and all matched items |
| 833 |
env []string |
| 834 |
query string |
| 835 |
} |
| 836 |
|
| 837 |
type previewResult struct { |
| 838 |
version int64 |
| 839 |
lines []string |
| 840 |
offset int |
| 841 |
spinner string |
| 842 |
} |
| 843 |
|
| 844 |
func toActions(types ...actionType) []*action { |
| 845 |
actions := make([]*action, len(types)) |
| 846 |
for idx, t := range types { |
| 847 |
actions[idx] = &action{t: t, a: ""} |
| 848 |
} |
| 849 |
return actions |
| 850 |
} |
| 851 |
|
| 852 |
func defaultKeymap() map[tui.Event][]*action { |
| 853 |
keymap := make(map[tui.Event][]*action) |
| 854 |
add := func(e tui.EventType, a actionType) { |
| 855 |
keymap[e.AsEvent()] = toActions(a) |
| 856 |
} |
| 857 |
addEvent := func(e tui.Event, a actionType) { |
| 858 |
keymap[e] = toActions(a) |
| 859 |
} |
| 860 |
|
| 861 |
add(tui.Fatal, actFatal) |
| 862 |
add(tui.Invalid, actInvalid) |
| 863 |
add(tui.BracketedPasteBegin, actBracketedPasteBegin) |
| 864 |
add(tui.BracketedPasteEnd, actBracketedPasteEnd) |
| 865 |
add(tui.CtrlA, actBeginningOfLine) |
| 866 |
add(tui.CtrlB, actBackwardChar) |
| 867 |
add(tui.CtrlC, actAbort) |
| 868 |
add(tui.CtrlG, actAbort) |
| 869 |
add(tui.CtrlQ, actAbort) |
| 870 |
add(tui.Esc, actAbort) |
| 871 |
add(tui.CtrlD, actDeleteCharEof) |
| 872 |
add(tui.CtrlE, actEndOfLine) |
| 873 |
add(tui.CtrlF, actForwardChar) |
| 874 |
add(tui.Backspace, actBackwardDeleteChar) |
| 875 |
add(tui.CtrlBackspace, actBackwardDeleteChar) |
| 876 |
add(tui.Tab, actToggleDown) |
| 877 |
add(tui.ShiftTab, actToggleUp) |
| 878 |
add(tui.CtrlJ, actDown) |
| 879 |
add(tui.CtrlK, actUp) |
| 880 |
add(tui.CtrlL, actClearScreen) |
| 881 |
add(tui.Enter, actAccept) |
| 882 |
add(tui.CtrlN, actDownMatch) |
| 883 |
add(tui.CtrlP, actUpMatch) |
| 884 |
add(tui.AltDown, actDownMatch) |
| 885 |
add(tui.AltUp, actUpMatch) |
| 886 |
add(tui.CtrlU, actUnixLineDiscard) |
| 887 |
add(tui.CtrlW, actUnixWordRubout) |
| 888 |
add(tui.CtrlY, actYank) |
| 889 |
if !util.IsWindows() { |
| 890 |
add(tui.CtrlZ, actSigStop) |
| 891 |
} |
| 892 |
add(tui.CtrlSlash, actToggleWrapWord) |
| 893 |
addEvent(tui.AltKey('/'), actToggleWrapWord) |
| 894 |
|
| 895 |
addEvent(tui.AltKey('b'), actBackwardWord) |
| 896 |
add(tui.ShiftLeft, actBackwardWord) |
| 897 |
add(tui.AltLeft, actBackwardWord) |
| 898 |
addEvent(tui.AltKey('f'), actForwardWord) |
| 899 |
add(tui.ShiftRight, actForwardWord) |
| 900 |
add(tui.AltRight, actForwardWord) |
| 901 |
addEvent(tui.AltKey('d'), actKillWord) |
| 902 |
add(tui.AltBackspace, actBackwardKillWord) |
| 903 |
|
| 904 |
add(tui.Up, actUp) |
| 905 |
add(tui.Down, actDown) |
| 906 |
add(tui.Left, actBackwardChar) |
| 907 |
add(tui.Right, actForwardChar) |
| 908 |
|
| 909 |
add(tui.Home, actBeginningOfLine) |
| 910 |
add(tui.End, actEndOfLine) |
| 911 |
add(tui.Delete, actDeleteChar) |
| 912 |
add(tui.PageUp, actPageUp) |
| 913 |
add(tui.PageDown, actPageDown) |
| 914 |
|
| 915 |
add(tui.ShiftUp, actPreviewUp) |
| 916 |
add(tui.ShiftDown, actPreviewDown) |
| 917 |
|
| 918 |
add(tui.Mouse, actMouse) |
| 919 |
add(tui.LeftClick, actClick) |
| 920 |
add(tui.RightClick, actToggle) |
| 921 |
add(tui.SLeftClick, actToggle) |
| 922 |
add(tui.SRightClick, actToggle) |
| 923 |
|
| 924 |
add(tui.ScrollUp, actUp) |
| 925 |
add(tui.ScrollDown, actDown) |
| 926 |
keymap[tui.SScrollUp.AsEvent()] = toActions(actToggle, actUp) |
| 927 |
keymap[tui.SScrollDown.AsEvent()] = toActions(actToggle, actDown) |
| 928 |
|
| 929 |
add(tui.PreviewScrollUp, actPreviewUp) |
| 930 |
add(tui.PreviewScrollDown, actPreviewDown) |
| 931 |
return keymap |
| 932 |
} |
| 933 |
|
| 934 |
func trimQuery(query string) []rune { |
| 935 |
return []rune(strings.ReplaceAll(query, "\t", " ")) |
| 936 |
} |
| 937 |
|
| 938 |
func mayTriggerPreview(opts *Options) bool { |
| 939 |
if opts.ListenAddr != nil { |
| 940 |
return true |
| 941 |
} |
| 942 |
for _, actions := range opts.Keymap { |
| 943 |
for _, action := range actions { |
| 944 |
switch action.t { |
| 945 |
case actPreview, actChangePreview, actTransform, actBgTransform: |
| 946 |
return true |
| 947 |
} |
| 948 |
} |
| 949 |
} |
| 950 |
return false |
| 951 |
} |
| 952 |
|
| 953 |
func makeSpinner(unicode bool) []string { |
| 954 |
if unicode { |
| 955 |
return []string{`⠋`, `⠙`, `⠹`, `⠸`, `⠼`, `⠴`, `⠦`, `⠧`, `⠇`, `⠏`} |
| 956 |
} |
| 957 |
return []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`} |
| 958 |
} |
| 959 |
|
| 960 |
func evaluateHeight(opts *Options, termHeight int) int { |
| 961 |
size := opts.Height.size |
| 962 |
if opts.Height.percent { |
| 963 |
if opts.Height.inverse { |
| 964 |
size = 100 - size |
| 965 |
} |
| 966 |
return max(int(size*float64(termHeight)/100.0), opts.MinHeight) |
| 967 |
} |
| 968 |
if opts.Height.inverse { |
| 969 |
size = float64(termHeight) - size |
| 970 |
} |
| 971 |
return int(size) |
| 972 |
} |
| 973 |
|
| 974 |
// NewTerminal returns new Terminal object |
| 975 |
func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor) (*Terminal, error) { |
| 976 |
input := trimQuery(opts.Query) |
| 977 |
var delay time.Duration |
| 978 |
if opts.Sync { |
| 979 |
delay = 0 |
| 980 |
} else if opts.Tac { |
| 981 |
delay = initialDelayTac |
| 982 |
} else { |
| 983 |
delay = initialDelay |
| 984 |
} |
| 985 |
var previewBox *util.EventBox |
| 986 |
// We need to start the previewer even when --preview option is not specified |
| 987 |
// * if HTTP server is enabled |
| 988 |
// * if 'preview' or 'change-preview' action is bound to a key |
| 989 |
// * if 'transform' action is bound to a key |
| 990 |
if len(opts.Preview.command) > 0 || mayTriggerPreview(opts) { |
| 991 |
previewBox = util.NewEventBox() |
| 992 |
} |
| 993 |
var renderer tui.Renderer |
| 994 |
fullscreen := !opts.Height.auto && (opts.Height.size == 0 || opts.Height.percent && opts.Height.size == 100) |
| 995 |
var err error |
| 996 |
// Reuse ttyin if available to avoid having multiple file descriptors open |
| 997 |
// when you run fzf multiple times in your Go program. Closing it is known to |
| 998 |
// cause problems with 'become' action and invalid terminal state after exit. |
| 999 |
if ttyin == nil { |
| 1000 |
if ttyin, err = tui.TtyIn(opts.TtyDefault); err != nil { |
| 1001 |
return nil, err |
| 1002 |
} |
| 1003 |
} |
| 1004 |
if fullscreen { |
| 1005 |
if tui.HasFullscreenRenderer() { |
| 1006 |
renderer = tui.NewFullscreenRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop) |
| 1007 |
} else { |
| 1008 |
renderer, err = tui.NewLightRenderer(opts.TtyDefault, ttyin, opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, |
| 1009 |
true, func(h int) int { return h }) |
| 1010 |
} |
| 1011 |
} else { |
| 1012 |
maxHeightFunc := func(termHeight int) int { |
| 1013 |
// Minimum height required to render fzf excluding margin and padding |
| 1014 |
effectiveMinHeight := minHeight |
| 1015 |
if previewBox != nil && opts.Preview.aboveOrBelow() { |
| 1016 |
effectiveMinHeight += 1 + borderLines(opts.Preview.Border(opts.Layout)) |
| 1017 |
} |
| 1018 |
if opts.noSeparatorLine() { |
| 1019 |
effectiveMinHeight-- |
| 1020 |
} |
| 1021 |
effectiveMinHeight += borderLines(opts.BorderShape) |
| 1022 |
return min(termHeight, max(evaluateHeight(opts, termHeight), effectiveMinHeight)) |
| 1023 |
} |
| 1024 |
renderer, err = tui.NewLightRenderer(opts.TtyDefault, ttyin, opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, false, maxHeightFunc) |
| 1025 |
} |
| 1026 |
if err != nil { |
| 1027 |
return nil, err |
| 1028 |
} |
| 1029 |
if opts.Inputless { |
| 1030 |
renderer.HideCursor() |
| 1031 |
} |
| 1032 |
wordRubout := "[^\\pL\\pN][\\pL\\pN]" |
| 1033 |
wordNext := "[\\pL\\pN][^\\pL\\pN]|(.$)" |
| 1034 |
subWordRubout := "[a-z][A-Z]|[^\\pL\\pN][\\pL\\pN]" |
| 1035 |
subWordNext := "[a-z][A-Z]|[\\pL\\pN][^\\pL\\pN]|(.$)" |
| 1036 |
if opts.FileWord { |
| 1037 |
sep := regexp.QuoteMeta(string(os.PathSeparator)) |
| 1038 |
wordRubout = fmt.Sprintf("%s[^%s]", sep, sep) |
| 1039 |
wordNext = fmt.Sprintf("[^%s]%s|(.$)", sep, sep) |
| 1040 |
} |
| 1041 |
keymapCopy := maps.Clone(opts.Keymap) |
| 1042 |
|
| 1043 |
em := EmptyMerger(revision{}) |
| 1044 |
t := Terminal{ |
| 1045 |
initDelay: delay, |
| 1046 |
infoCommand: opts.InfoCommand, |
| 1047 |
infoStyle: opts.InfoStyle, |
| 1048 |
infoPrefix: opts.InfoPrefix, |
| 1049 |
ghost: opts.Ghost, |
| 1050 |
separator: nil, |
| 1051 |
spinner: makeSpinner(opts.Unicode), |
| 1052 |
promptString: opts.Prompt, |
| 1053 |
queryLen: [2]int{0, 0}, |
| 1054 |
layout: opts.Layout, |
| 1055 |
fullscreen: fullscreen, |
| 1056 |
keepRight: opts.KeepRight, |
| 1057 |
hscroll: opts.Hscroll, |
| 1058 |
hscrollOff: opts.HscrollOff, |
| 1059 |
scrollOff: opts.ScrollOff, |
| 1060 |
pointer: *opts.Pointer, |
| 1061 |
pointerLen: uniseg.StringWidth(*opts.Pointer), |
| 1062 |
marker: *opts.Marker, |
| 1063 |
markerLen: uniseg.StringWidth(*opts.Marker), |
| 1064 |
markerMultiLine: *opts.MarkerMulti, |
| 1065 |
wordRubout: wordRubout, |
| 1066 |
wordNext: wordNext, |
| 1067 |
subWordRubout: subWordRubout, |
| 1068 |
subWordNext: subWordNext, |
| 1069 |
cx: len(input), |
| 1070 |
cy: 0, |
| 1071 |
offset: 0, |
| 1072 |
xoffset: 0, |
| 1073 |
yanked: []rune{}, |
| 1074 |
input: input, |
| 1075 |
multi: opts.Multi, |
| 1076 |
multiLine: opts.ReadZero && opts.MultiLine, |
| 1077 |
wrap: opts.Wrap, |
| 1078 |
wrapWord: opts.WrapWord, |
| 1079 |
sort: opts.Sort > 0, |
| 1080 |
toggleSort: opts.ToggleSort, |
| 1081 |
track: opts.Track, |
| 1082 |
idNth: opts.IdNth, |
| 1083 |
targetIndex: minItem.Index(), |
| 1084 |
delimiter: opts.Delimiter, |
| 1085 |
expect: opts.Expect, |
| 1086 |
keymap: opts.Keymap, |
| 1087 |
keymapOrg: keymapCopy, |
| 1088 |
pressed: "", |
| 1089 |
printQuery: opts.PrintQuery, |
| 1090 |
history: opts.History, |
| 1091 |
margin: opts.Margin, |
| 1092 |
padding: opts.Padding, |
| 1093 |
unicode: opts.Unicode, |
| 1094 |
listenAddr: opts.ListenAddr, |
| 1095 |
listenUnsafe: opts.Unsafe, |
| 1096 |
borderShape: opts.BorderShape, |
| 1097 |
listBorderShape: opts.ListBorderShape, |
| 1098 |
inputBorderShape: opts.InputBorderShape, |
| 1099 |
headerBorderShape: opts.HeaderBorderShape, |
| 1100 |
headerLinesShape: opts.HeaderLinesShape, |
| 1101 |
footerBorderShape: opts.FooterBorderShape, |
| 1102 |
borderWidth: 1, |
| 1103 |
listLabel: nil, |
| 1104 |
listLabelOpts: opts.ListLabel, |
| 1105 |
borderLabel: nil, |
| 1106 |
borderLabelOpts: opts.BorderLabel, |
| 1107 |
previewLabel: nil, |
| 1108 |
previewLabelOpts: opts.PreviewLabel, |
| 1109 |
inputLabel: nil, |
| 1110 |
inputLabelOpts: opts.InputLabel, |
| 1111 |
headerLabel: nil, |
| 1112 |
headerLabelOpts: opts.HeaderLabel, |
| 1113 |
footerLabel: nil, |
| 1114 |
footerLabelOpts: opts.FooterLabel, |
| 1115 |
cleanExit: opts.ClearOnExit, |
| 1116 |
executor: executor, |
| 1117 |
paused: opts.Phony, |
| 1118 |
inputless: opts.Inputless, |
| 1119 |
cycle: opts.Cycle, |
| 1120 |
highlightLine: opts.CursorLine, |
| 1121 |
headerVisible: true, |
| 1122 |
headerFirst: opts.HeaderFirst, |
| 1123 |
headerLines: opts.HeaderLines, |
| 1124 |
gap: opts.Gap, |
| 1125 |
header: []Item{}, |
| 1126 |
footer: opts.Footer, |
| 1127 |
header0: opts.Header, |
| 1128 |
ansi: opts.Ansi, |
| 1129 |
freezeLeft: opts.FreezeLeft, |
| 1130 |
freezeRight: opts.FreezeRight, |
| 1131 |
nthAttr: opts.Theme.Nth.Attr, |
| 1132 |
nth: opts.Nth, |
| 1133 |
nthCurrent: opts.Nth, |
| 1134 |
withNthDefault: opts.WithNthExpr, |
| 1135 |
withNthExpr: opts.WithNthExpr, |
| 1136 |
withNthEnabled: opts.WithNth != nil, |
| 1137 |
tabstop: opts.Tabstop, |
| 1138 |
raw: opts.Raw, |
| 1139 |
hasStartActions: false, |
| 1140 |
hasResultActions: false, |
| 1141 |
hasFocusActions: false, |
| 1142 |
hasLoadActions: false, |
| 1143 |
triggerLoad: false, |
| 1144 |
reading: true, |
| 1145 |
running: util.NewAtomicBool(true), |
| 1146 |
failed: nil, |
| 1147 |
jumping: jumpDisabled, |
| 1148 |
jumpLabels: opts.JumpLabels, |
| 1149 |
printer: opts.Printer, |
| 1150 |
printsep: opts.PrintSep, |
| 1151 |
proxyScript: opts.ProxyScript, |
| 1152 |
setNativeLabel: nativeLabelSetter(), |
| 1153 |
merger: em, |
| 1154 |
passMerger: em, |
| 1155 |
resultMerger: em, |
| 1156 |
matchMap: make(map[int32]Result), |
| 1157 |
selected: make(map[int32]selectedItem), |
| 1158 |
runningCmds: util.NewConcurrentSet[*runningCmd](), |
| 1159 |
reqBox: util.NewEventBox(), |
| 1160 |
initialPreviewOpts: opts.Preview, |
| 1161 |
previewOpts: opts.Preview, |
| 1162 |
activePreviewOpts: &opts.Preview, |
| 1163 |
previewer: previewer{0, []string{}, 0, false, true, disabledState, "", []bool{}, [2]int{0, 0}}, |
| 1164 |
previewed: previewed{0, 0, 0, false, false, false, false}, |
| 1165 |
previewBox: previewBox, |
| 1166 |
eventBox: eventBox, |
| 1167 |
mutex: sync.Mutex{}, |
| 1168 |
uiMutex: sync.Mutex{}, |
| 1169 |
suppress: true, |
| 1170 |
slab: util.MakeSlab(slab16Size, slab32Size), |
| 1171 |
theme: opts.Theme, |
| 1172 |
startChan: make(chan fitpad, 1), |
| 1173 |
killChan: make(chan bool), |
| 1174 |
killedChan: make(chan bool), |
| 1175 |
serverInputChan: make(chan []*action, 100), |
| 1176 |
callbackChan: make(chan versionedCallback, maxBgProcesses), |
| 1177 |
bgQueue: make(map[action][]func(bool)), |
| 1178 |
bgSemaphore: make(chan struct{}, maxBgProcesses), |
| 1179 |
bgSemaphores: make(map[action]chan struct{}), |
| 1180 |
keyChan: make(chan tui.Event), |
| 1181 |
eventChan: make(chan tui.Event, 7), // start | (load + result + result-final + zero|one) | (focus) | (resize) |
| 1182 |
timerChan: make(chan tui.Event), // unbuffered: every() ticks coalesce when main loop is busy |
| 1183 |
tui: renderer, |
| 1184 |
ttyDefault: opts.TtyDefault, |
| 1185 |
ttyin: ttyin, |
| 1186 |
initFunc: func() error { return renderer.Init() }, |
| 1187 |
executing: util.NewAtomicBool(false), |
| 1188 |
lastAction: actStart, |
| 1189 |
lastFocus: minItem.Index(), |
| 1190 |
lastActivity: time.Now(), |
| 1191 |
numLinesCache: make(map[int32]numLinesCacheValue), |
| 1192 |
// The initial load counts as a search in progress ('start:wait'). |
| 1193 |
// Set before the reader starts so the first final result clears it. |
| 1194 |
wait: waitState{searching: true}} |
| 1195 |
if opts.AcceptNth != nil { |
| 1196 |
t.acceptNth = opts.AcceptNth(t.delimiter) |
| 1197 |
} |
| 1198 |
|
| 1199 |
baseTheme := opts.BaseTheme |
| 1200 |
if baseTheme == nil { |
| 1201 |
baseTheme = renderer.DefaultTheme() |
| 1202 |
} |
| 1203 |
// If the list border can't host an inline separator, the runtime later coerces |
| 1204 |
// BorderInline to BorderLine. Mirror that here so theme color inheritance matches |
| 1205 |
// the final rendering rather than the user's requested shape. |
| 1206 |
inlineListSupported := opts.ListBorderShape.HasTop() && opts.ListBorderShape.HasBottom() |
| 1207 |
headerInline := inlineListSupported && (opts.HeaderBorderShape == tui.BorderInline || opts.HeaderLinesShape == tui.BorderInline) |
| 1208 |
footerInline := inlineListSupported && opts.FooterBorderShape == tui.BorderInline |
| 1209 |
hasHeader := opts.HeaderBorderShape.Visible() || opts.HeaderLinesShape.Visible() |
| 1210 |
// This should be called before accessing tui.Color* |
| 1211 |
tui.InitTheme(opts.Theme, baseTheme, opts.Bold, opts.Black, opts.InputBorderShape.Visible(), hasHeader, headerInline, footerInline) |
| 1212 |
|
| 1213 |
// Gutter character |
| 1214 |
var gutterChar, gutterRawChar string |
| 1215 |
if opts.Gutter != nil { |
| 1216 |
gutterChar = *opts.Gutter |
| 1217 |
} else if t.unicode { |
| 1218 |
gutterChar = "▌" |
| 1219 |
} else { |
| 1220 |
gutterChar = " " |
| 1221 |
t.gutterReverse = true |
| 1222 |
} |
| 1223 |
|
| 1224 |
if opts.GutterRaw != nil { |
| 1225 |
gutterRawChar = *opts.GutterRaw |
| 1226 |
} else if t.unicode { |
| 1227 |
gutterRawChar = "▖" |
| 1228 |
} else { |
| 1229 |
gutterRawChar = ":" |
| 1230 |
t.gutterRawReverse = false |
| 1231 |
} |
| 1232 |
|
| 1233 |
t.prompt, t.promptLen = t.parsePrompt(opts.Prompt) |
| 1234 |
// Pre-calculated empty pointer and marker signs |
| 1235 |
if t.pointerLen == 0 { |
| 1236 |
t.pointerEmpty = "" |
| 1237 |
t.pointerEmptyRaw = "" |
| 1238 |
} else { |
| 1239 |
t.pointerEmpty = gutterChar + strings.Repeat(" ", max(0, t.pointerLen-1)) |
| 1240 |
t.pointerEmptyRaw = gutterRawChar + strings.Repeat(" ", max(0, t.pointerLen-1)) |
| 1241 |
} |
| 1242 |
t.markerEmpty = strings.Repeat(" ", t.markerLen) |
| 1243 |
|
| 1244 |
// Labels |
| 1245 |
t.listLabel, t.listLabelLen = t.ansiLabelPrinter(opts.ListLabel.label, &tui.ColListLabel, false) |
| 1246 |
t.borderLabel, t.borderLabelLen = t.ansiLabelPrinter(opts.BorderLabel.label, &tui.ColBorderLabel, false) |
| 1247 |
t.previewLabel, t.previewLabelLen = t.ansiLabelPrinter(opts.PreviewLabel.label, &tui.ColPreviewLabel, false) |
| 1248 |
t.inputLabel, t.inputLabelLen = t.ansiLabelPrinter(opts.InputLabel.label, &tui.ColInputLabel, false) |
| 1249 |
t.headerLabel, t.headerLabelLen = t.ansiLabelPrinter(opts.HeaderLabel.label, &tui.ColHeaderLabel, false) |
| 1250 |
t.footerLabel, t.footerLabelLen = t.ansiLabelPrinter(opts.FooterLabel.label, &tui.ColFooterLabel, false) |
| 1251 |
|
| 1252 |
// Determine border shape |
| 1253 |
if t.borderShape == tui.BorderLine { |
| 1254 |
if t.fullscreen { |
| 1255 |
t.borderShape = tui.BorderNone |
| 1256 |
} else { |
| 1257 |
t.borderShape = tui.BorderTop |
| 1258 |
} |
| 1259 |
} |
| 1260 |
|
| 1261 |
// Determine input border shape |
| 1262 |
t.inputBorderShape = resolveInputBorderShape(t.layout, t.inputBorderShape) |
| 1263 |
|
| 1264 |
// Inline borders are embedded between the list's top and bottom horizontals. |
| 1265 |
// Shapes missing either one (none/phantom/line/single-sided) fall back to a plain |
| 1266 |
// horizontal separator (same as BorderLine). |
| 1267 |
inlineSupported := t.listBorderShape.HasTop() && t.listBorderShape.HasBottom() |
| 1268 |
if !inlineSupported { |
| 1269 |
if t.headerBorderShape == tui.BorderInline { |
| 1270 |
t.headerBorderShape = tui.BorderLine |
| 1271 |
} |
| 1272 |
if t.headerLinesShape == tui.BorderInline { |
| 1273 |
t.headerLinesShape = tui.BorderLine |
| 1274 |
} |
| 1275 |
if t.footerBorderShape == tui.BorderInline { |
| 1276 |
t.footerBorderShape = tui.BorderLine |
| 1277 |
} |
| 1278 |
} |
| 1279 |
|
| 1280 |
// Determine header border shape |
| 1281 |
if t.headerBorderShape == tui.BorderLine { |
| 1282 |
if t.layout == layoutReverse { |
| 1283 |
t.headerBorderShape = tui.BorderBottom |
| 1284 |
} else { |
| 1285 |
t.headerBorderShape = tui.BorderTop |
| 1286 |
} |
| 1287 |
} |
| 1288 |
|
| 1289 |
// Determine header lines border shape |
| 1290 |
if t.headerLinesShape == tui.BorderLine { |
| 1291 |
if t.layout == layoutDefault { |
| 1292 |
t.headerLinesShape = tui.BorderTop |
| 1293 |
} else { |
| 1294 |
t.headerLinesShape = tui.BorderBottom |
| 1295 |
} |
| 1296 |
} |
| 1297 |
|
| 1298 |
// Determine footer border shape |
| 1299 |
if t.footerBorderShape == tui.BorderLine { |
| 1300 |
if t.layout == layoutReverse { |
| 1301 |
t.footerBorderShape = tui.BorderTop |
| 1302 |
} else { |
| 1303 |
t.footerBorderShape = tui.BorderBottom |
| 1304 |
} |
| 1305 |
} |
| 1306 |
|
| 1307 |
// The default separator can be suppressed at runtime depending on the |
| 1308 |
// window layout (see separatorLength) |
| 1309 |
t.separatorAuto = opts.Separator == nil |
| 1310 |
bar := "─" |
| 1311 |
if opts.Separator != nil { |
| 1312 |
bar = *opts.Separator |
| 1313 |
} else if !t.unicode { |
| 1314 |
bar = "-" |
| 1315 |
} |
| 1316 |
if len(bar) > 0 { |
| 1317 |
t.separator, t.separatorLen = t.ansiLabelPrinter(bar, &tui.ColSeparator, true) |
| 1318 |
} |
| 1319 |
|
| 1320 |
// Gap line |
| 1321 |
if t.gap > 0 && len(*opts.GapLine) > 0 { |
| 1322 |
t.gapLine, t.gapLineLen = t.ansiLabelPrinter(*opts.GapLine, &tui.ColGapLine, true) |
| 1323 |
} |
| 1324 |
|
| 1325 |
if opts.Ellipsis != nil { |
| 1326 |
t.ellipsis = *opts.Ellipsis |
| 1327 |
} else if t.unicode { |
| 1328 |
t.ellipsis = "··" |
| 1329 |
} else { |
| 1330 |
t.ellipsis = ".." |
| 1331 |
} |
| 1332 |
|
| 1333 |
if t.unicode { |
| 1334 |
t.wrapSign = "↳ " |
| 1335 |
t.borderWidth = uniseg.StringWidth("│") |
| 1336 |
} else { |
| 1337 |
t.wrapSign = "> " |
| 1338 |
} |
| 1339 |
if opts.WrapSign != nil { |
| 1340 |
t.wrapSign = *opts.WrapSign |
| 1341 |
} |
| 1342 |
t.wrapSign, t.wrapSignWidth = t.processTabsStr(t.wrapSign, 0) |
| 1343 |
t.previewWrapSign = t.wrapSign |
| 1344 |
t.previewWrapSignWidth = t.wrapSignWidth |
| 1345 |
if opts.PreviewWrapSign != nil { |
| 1346 |
t.previewWrapSign, t.previewWrapSignWidth = t.processTabsStr(*opts.PreviewWrapSign, 0) |
| 1347 |
} |
| 1348 |
if opts.Scrollbar == nil { |
| 1349 |
if t.unicode && t.borderWidth == 1 { |
| 1350 |
t.scrollbar = "│" |
| 1351 |
} else { |
| 1352 |
t.scrollbar = "|" |
| 1353 |
} |
| 1354 |
t.previewScrollbar = t.scrollbar |
| 1355 |
} else { |
| 1356 |
runes := []rune(*opts.Scrollbar) |
| 1357 |
if len(runes) > 0 { |
| 1358 |
t.scrollbar = string(runes[0]) |
| 1359 |
t.previewScrollbar = t.scrollbar |
| 1360 |
if len(runes) > 1 { |
| 1361 |
t.previewScrollbar = string(runes[1]) |
| 1362 |
} |
| 1363 |
} |
| 1364 |
} |
| 1365 |
|
| 1366 |
var resizeActions []*action |
| 1367 |
resizeActions, t.hasResizeActions = t.keymap[tui.Resize.AsEvent()] |
| 1368 |
if t.tui.ShouldEmitResizeEvent() { |
| 1369 |
t.keymap[tui.Resize.AsEvent()] = append(toActions(actClearScreen), resizeActions...) |
| 1370 |
} |
| 1371 |
_, t.hasStartActions = t.keymap[tui.Start.AsEvent()] |
| 1372 |
_, t.hasResultActions = t.keymap[tui.Result.AsEvent()] |
| 1373 |
if _, prs := t.keymap[tui.ResultFinal.AsEvent()]; prs { |
| 1374 |
t.hasResultActions = true |
| 1375 |
} |
| 1376 |
_, t.hasFocusActions = t.keymap[tui.Focus.AsEvent()] |
| 1377 |
_, t.hasLoadActions = t.keymap[tui.Load.AsEvent()] |
| 1378 |
|
| 1379 |
if t.listenAddr != nil { |
| 1380 |
listener, port, err := startHttpServer(*t.listenAddr, t.serverInputChan, t.dumpStatus) |
| 1381 |
if err != nil { |
| 1382 |
return nil, err |
| 1383 |
} |
| 1384 |
t.listener = listener |
| 1385 |
if port > 0 { |
| 1386 |
t.listenPort = &port |
| 1387 |
} |
| 1388 |
} |
| 1389 |
|
| 1390 |
if t.hasStartActions { |
| 1391 |
t.eventChan <- tui.Start.AsEvent() |
| 1392 |
} |
| 1393 |
|
| 1394 |
return &t, nil |
| 1395 |
} |
| 1396 |
|
| 1397 |
func (t *Terminal) deferActivation() bool { |
| 1398 |
return t.initDelay == 0 && (t.hasStartActions || t.hasLoadActions || t.hasResultActions || t.hasFocusActions) |
| 1399 |
} |
| 1400 |
|
| 1401 |
func (t *Terminal) environ() []string { |
| 1402 |
return t.environImpl(false) |
| 1403 |
} |
| 1404 |
|
| 1405 |
func (t *Terminal) environForPreview() []string { |
| 1406 |
return t.environImpl(true) |
| 1407 |
} |
| 1408 |
|
| 1409 |
func (t *Terminal) environImpl(forPreview bool) []string { |
| 1410 |
env := os.Environ() |
| 1411 |
if t.listenAddr != nil && len(t.listenAddr.sock) > 0 { |
| 1412 |
env = append(env, "FZF_SOCK="+t.listenAddr.sock) |
| 1413 |
} |
| 1414 |
if t.listenPort != nil { |
| 1415 |
env = append(env, fmt.Sprintf("FZF_PORT=%d", *t.listenPort)) |
| 1416 |
} |
| 1417 |
env = append(env, "FZF_QUERY="+string(t.input)) |
| 1418 |
env = append(env, "FZF_ACTION="+t.lastAction.Name()) |
| 1419 |
env = append(env, "FZF_KEY="+t.lastKey) |
| 1420 |
idleMs := time.Since(t.lastActivity).Milliseconds() |
| 1421 |
env = append(env, fmt.Sprintf("FZF_IDLE_TIME=%d", idleMs/1000)) |
| 1422 |
env = append(env, fmt.Sprintf("FZF_IDLE_TIME_MS=%d", idleMs)) |
| 1423 |
env = append(env, "FZF_PROMPT="+string(t.promptString)) |
| 1424 |
env = append(env, "FZF_GHOST="+string(t.ghost)) |
| 1425 |
env = append(env, "FZF_POINTER="+string(t.pointer)) |
| 1426 |
env = append(env, "FZF_PREVIEW_LABEL="+t.previewLabelOpts.label) |
| 1427 |
env = append(env, "FZF_BORDER_LABEL="+t.borderLabelOpts.label) |
| 1428 |
env = append(env, "FZF_LIST_LABEL="+t.listLabelOpts.label) |
| 1429 |
env = append(env, "FZF_INPUT_LABEL="+t.inputLabelOpts.label) |
| 1430 |
env = append(env, "FZF_HEADER_LABEL="+t.headerLabelOpts.label) |
| 1431 |
direction := "down" |
| 1432 |
if t.layout == layoutDefault { |
| 1433 |
direction = "up" |
| 1434 |
} |
| 1435 |
env = append(env, "FZF_DIRECTION="+direction) |
| 1436 |
if len(t.nthCurrent) > 0 { |
| 1437 |
env = append(env, "FZF_NTH="+RangesToString(t.nthCurrent)) |
| 1438 |
} |
| 1439 |
if len(t.withNthExpr) > 0 { |
| 1440 |
env = append(env, "FZF_WITH_NTH="+t.withNthExpr) |
| 1441 |
} |
| 1442 |
if t.raw { |
| 1443 |
val := "0" |
| 1444 |
if t.isCurrentItemMatch() { |
| 1445 |
val = "1" |
| 1446 |
} |
| 1447 |
env = append(env, "FZF_RAW="+val) |
| 1448 |
} |
| 1449 |
inputState := "enabled" |
| 1450 |
if t.inputless { |
| 1451 |
inputState = "hidden" |
| 1452 |
} else if t.paused { |
| 1453 |
inputState = "disabled" |
| 1454 |
} |
| 1455 |
if t.wrap { |
| 1456 |
if t.wrapWord { |
| 1457 |
env = append(env, "FZF_WRAP=word") |
| 1458 |
} else { |
| 1459 |
env = append(env, "FZF_WRAP=char") |
| 1460 |
} |
| 1461 |
} |
| 1462 |
env = append(env, "FZF_INPUT_STATE="+inputState) |
| 1463 |
env = append(env, fmt.Sprintf("FZF_TOTAL_COUNT=%d", t.count)) |
| 1464 |
env = append(env, fmt.Sprintf("FZF_MATCH_COUNT=%d", t.resultMerger.Length())) |
| 1465 |
env = append(env, fmt.Sprintf("FZF_SELECT_COUNT=%d", len(t.selected))) |
| 1466 |
env = append(env, fmt.Sprintf("FZF_LINES=%d", t.areaLines)) |
| 1467 |
env = append(env, fmt.Sprintf("FZF_COLUMNS=%d", t.areaColumns)) |
| 1468 |
env = append(env, fmt.Sprintf("FZF_POS=%d", min(t.merger.Length(), t.cy+1))) |
| 1469 |
if item := t.currentItem(); item != nil { |
| 1470 |
// Skip if the value contains a NUL byte (exec(2) would reject the env) |
| 1471 |
// or is too large (a huge item can overflow ARG_MAX and break exec |
| 1472 |
// entirely for preview and other child commands). |
| 1473 |
if s := item.AsString(t.ansi); !strings.ContainsRune(s, 0) && len(s) <= maxCurrentItemEnvSize { |
| 1474 |
env = append(env, "FZF_CURRENT_ITEM="+s) |
| 1475 |
} |
| 1476 |
} |
| 1477 |
env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_LINE=%d", t.clickHeaderLine)) |
| 1478 |
env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_COLUMN=%d", t.clickHeaderColumn)) |
| 1479 |
env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_LINE=%d", t.clickFooterLine)) |
| 1480 |
env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_COLUMN=%d", t.clickFooterColumn)) |
| 1481 |
env = t.addClickHeaderWord(env) |
| 1482 |
env = t.addClickFooterWord(env) |
| 1483 |
|
| 1484 |
// Add preview environment variables if preview is enabled |
| 1485 |
pwindowSize := t.pwindowSize() |
| 1486 |
if pwindowSize.Lines > 0 { |
| 1487 |
lines := fmt.Sprintf("LINES=%d", pwindowSize.Lines) |
| 1488 |
columns := fmt.Sprintf("COLUMNS=%d", pwindowSize.Columns) |
| 1489 |
if forPreview { |
| 1490 |
env = append(env, lines) |
| 1491 |
env = append(env, columns) |
| 1492 |
} |
| 1493 |
env = append(env, "FZF_PREVIEW_"+lines) |
| 1494 |
env = append(env, "FZF_PREVIEW_"+columns) |
| 1495 |
env = append(env, fmt.Sprintf("FZF_PREVIEW_TOP=%d", t.tui.Top()+t.pwindow.Top())) |
| 1496 |
env = append(env, fmt.Sprintf("FZF_PREVIEW_LEFT=%d", t.pwindow.Left())) |
| 1497 |
} |
| 1498 |
|
| 1499 |
return env |
| 1500 |
} |
| 1501 |
|
| 1502 |
func borderLines(shape tui.BorderShape) int { |
| 1503 |
lines := 0 |
| 1504 |
if shape.HasTop() { |
| 1505 |
lines++ |
| 1506 |
} |
| 1507 |
if shape.HasBottom() { |
| 1508 |
lines++ |
| 1509 |
} |
| 1510 |
return lines |
| 1511 |
} |
| 1512 |
|
| 1513 |
func borderColumns(shape tui.BorderShape, borderWidth int) int { |
| 1514 |
columns := 0 |
| 1515 |
if shape.HasLeft() { |
| 1516 |
columns += 1 + borderWidth |
| 1517 |
} |
| 1518 |
if shape.HasRight() { |
| 1519 |
columns += 1 + borderWidth |
| 1520 |
} |
| 1521 |
return columns |
| 1522 |
} |
| 1523 |
|
| 1524 |
func (t *Terminal) visibleHeaderLines() int { |
| 1525 |
if !t.headerVisible { |
| 1526 |
return 0 |
| 1527 |
} |
| 1528 |
return len(t.header0) + t.headerLines |
| 1529 |
} |
| 1530 |
|
| 1531 |
func (t *Terminal) visibleHeaderLinesInList() int { |
| 1532 |
if t.headerWindow != nil || t.headerLinesWindow != nil { |
| 1533 |
return 0 |
| 1534 |
} |
| 1535 |
return t.visibleHeaderLines() |
| 1536 |
} |
| 1537 |
|
| 1538 |
func (t *Terminal) visibleInputLinesInList() int { |
| 1539 |
if t.inputWindow != nil || t.inputless { |
| 1540 |
return 0 |
| 1541 |
} |
| 1542 |
if t.noSeparatorLine() { |
| 1543 |
return 1 |
| 1544 |
} |
| 1545 |
return 2 |
| 1546 |
} |
| 1547 |
|
| 1548 |
// Extra number of lines needed to display fzf |
| 1549 |
func (t *Terminal) extraLines() int { |
| 1550 |
// borderLines() reports zero for BorderInline, but addInline() still |
| 1551 |
// reserves a divider line for it |
| 1552 |
sectionLines := func(shape tui.BorderShape) int { |
| 1553 |
if shape == tui.BorderInline { |
| 1554 |
return 1 |
| 1555 |
} |
| 1556 |
return borderLines(shape) |
| 1557 |
} |
| 1558 |
extra := 0 |
| 1559 |
if !t.inputless { |
| 1560 |
extra++ |
| 1561 |
if !t.noSeparatorLine() { |
| 1562 |
extra++ |
| 1563 |
} |
| 1564 |
if t.inputBorderShape.Visible() { |
| 1565 |
extra += borderLines(t.inputBorderShape) |
| 1566 |
} |
| 1567 |
} |
| 1568 |
if t.listBorderShape.Visible() { |
| 1569 |
extra += borderLines(t.listBorderShape) |
| 1570 |
} |
| 1571 |
if t.headerVisible { |
| 1572 |
if t.hasHeaderWindow() { |
| 1573 |
extra += sectionLines(t.headerBorderShape) |
| 1574 |
} |
| 1575 |
extra += len(t.header0) |
| 1576 |
if w, shape := t.determineHeaderLinesShape(); w { |
| 1577 |
extra += sectionLines(shape) |
| 1578 |
} |
| 1579 |
extra += t.headerLines |
| 1580 |
} |
| 1581 |
if len(t.footer) > 0 { |
| 1582 |
extra += sectionLines(t.footerBorderShape) |
| 1583 |
extra += len(t.footer) |
| 1584 |
} |
| 1585 |
return extra |
| 1586 |
} |
| 1587 |
|
| 1588 |
func (t *Terminal) MaxFitAndPad() (int, int) { |
| 1589 |
_, screenHeight, marginInt, paddingInt := t.adjustMarginAndPadding() |
| 1590 |
padHeight := marginInt[0] + marginInt[2] + paddingInt[0] + paddingInt[2] |
| 1591 |
fit := screenHeight - padHeight - t.extraLines() |
| 1592 |
return fit, padHeight |
| 1593 |
} |
| 1594 |
|
| 1595 |
func (t *Terminal) ansiLabelPrinter(str string, color *tui.ColorPair, fill bool) (labelPrinter, int) { |
| 1596 |
// Nothing to do |
| 1597 |
if len(str) == 0 { |
| 1598 |
return nil, 0 |
| 1599 |
} |
| 1600 |
|
| 1601 |
// Extract ANSI color codes |
| 1602 |
str = firstLine(str) |
| 1603 |
text, colors, _ := extractColor(str, nil, nil) |
| 1604 |
runes := []rune(text) |
| 1605 |
|
| 1606 |
// Simpler printer for strings without ANSI colors or tab characters |
| 1607 |
if colors == nil && !strings.ContainsRune(text, '\t') { |
| 1608 |
length := util.StringWidth(text) |
| 1609 |
if length == 0 { |
| 1610 |
return nil, 0 |
| 1611 |
} |
| 1612 |
printFn := func(window tui.Window, limit int) { |
| 1613 |
ellipsis := []rune{} |
| 1614 |
ellipsisWidth := 0 |
| 1615 |
if !fill { |
| 1616 |
ellipsis, ellipsisWidth = util.Truncate(t.ellipsis, limit) |
| 1617 |
} |
| 1618 |
if length > limit { |
| 1619 |
trimmedRunes, _ := t.trimRight(runes, limit-ellipsisWidth) |
| 1620 |
window.CPrint(*color, string(trimmedRunes)+string(ellipsis)) |
| 1621 |
} else if fill { |
| 1622 |
window.CPrint(*color, util.RepeatToFill(text, length, limit)) |
| 1623 |
} else { |
| 1624 |
window.CPrint(*color, text) |
| 1625 |
} |
| 1626 |
} |
| 1627 |
return printFn, length |
| 1628 |
} |
| 1629 |
|
| 1630 |
// Printer that correctly handles ANSI color codes and tab characters |
| 1631 |
item := &Item{text: util.RunesToChars(runes), colors: colors} |
| 1632 |
length := t.displayWidth(runes) |
| 1633 |
if length == 0 { |
| 1634 |
return nil, 0 |
| 1635 |
} |
| 1636 |
result := Result{item: item} |
| 1637 |
var offsets []colorOffset |
| 1638 |
printFn := func(window tui.Window, limit int) { |
| 1639 |
if offsets == nil { |
| 1640 |
// tui.Col* are not initialized until renderer.Init() |
| 1641 |
offsets = result.colorOffsets(nil, nil, t.theme, *color, *color, t.nthAttr, 0, false) |
| 1642 |
} |
| 1643 |
for limit > 0 { |
| 1644 |
if length > limit { |
| 1645 |
trimmedRunes, _ := t.trimRight(runes, limit) |
| 1646 |
t.printColoredString(window, trimmedRunes, offsets, *color) |
| 1647 |
break |
| 1648 |
} else if fill { |
| 1649 |
t.printColoredString(window, runes, offsets, *color) |
| 1650 |
limit -= length |
| 1651 |
} else { |
| 1652 |
t.printColoredString(window, runes, offsets, *color) |
| 1653 |
break |
| 1654 |
} |
| 1655 |
} |
| 1656 |
} |
| 1657 |
return printFn, length |
| 1658 |
} |
| 1659 |
|
| 1660 |
// Temporarily switch 'window' so that we can use the existing windows with |
| 1661 |
// a different window |
| 1662 |
func (t *Terminal) withWindow(w tui.Window, f func()) { |
| 1663 |
prevWindow := t.window |
| 1664 |
if w != nil { |
| 1665 |
t.window = w |
| 1666 |
} |
| 1667 |
f() |
| 1668 |
t.window = prevWindow |
| 1669 |
} |
| 1670 |
|
| 1671 |
func (t *Terminal) parsePrompt(prompt string) (func(), int) { |
| 1672 |
var state *ansiState |
| 1673 |
prompt = firstLine(prompt) |
| 1674 |
trimmed, colors, _ := extractColor(prompt, state, nil) |
| 1675 |
item := &Item{text: util.ToChars([]byte(trimmed)), colors: colors} |
| 1676 |
|
| 1677 |
// "Prompt> " |
| 1678 |
// ------- // Do not apply ANSI attributes to the trailing whitespaces |
| 1679 |
// // unless the part has a non-default ANSI state |
| 1680 |
loc := whiteSuffix.FindStringIndex(trimmed) |
| 1681 |
if loc != nil { |
| 1682 |
blankState := ansiOffset{[2]int32{int32(loc[0]), int32(loc[1])}, ansiState{tui.ColPrompt.Fg(), tui.ColPrompt.Bg(), -1, tui.AttrClear, -1, nil}} |
| 1683 |
if item.colors != nil { |
| 1684 |
lastColor := (*item.colors)[len(*item.colors)-1] |
| 1685 |
if lastColor.offset[1] < int32(loc[1]) { |
| 1686 |
blankState.offset[0] = lastColor.offset[1] |
| 1687 |
colors := append(*item.colors, blankState) |
| 1688 |
item.colors = &colors |
| 1689 |
} |
| 1690 |
} else { |
| 1691 |
colors := []ansiOffset{blankState} |
| 1692 |
item.colors = &colors |
| 1693 |
} |
| 1694 |
} |
| 1695 |
output := func() { |
| 1696 |
wrap := t.wrap |
| 1697 |
t.wrap = false |
| 1698 |
t.withWindow(t.inputWindow, func() { |
| 1699 |
preTask := func(markerClass) int { |
| 1700 |
return 1 |
| 1701 |
} |
| 1702 |
t.printHighlighted( |
| 1703 |
Result{item: item}, tui.ColPrompt, tui.ColPrompt, false, false, false, 0, 0, true, preTask, nil, 0) |
| 1704 |
}) |
| 1705 |
t.wrap = wrap |
| 1706 |
} |
| 1707 |
_, promptLen := t.processTabsStr(trimmed, 0) |
| 1708 |
|
| 1709 |
return output, promptLen |
| 1710 |
} |
| 1711 |
|
| 1712 |
func (t *Terminal) noSeparatorLine() bool { |
| 1713 |
return t.inputless || noSeparatorLine(t.infoStyle, t.separatorLength() > 0) |
| 1714 |
} |
| 1715 |
|
| 1716 |
// Effective length of the horizontal separator. The default separator is |
| 1717 |
// suppressed when the input section is already visually separated from the |
| 1718 |
// list section by a border line. |
| 1719 |
func (t *Terminal) separatorLength() int { |
| 1720 |
if t.separatorAuto && t.separatedByBorder() { |
| 1721 |
return 0 |
| 1722 |
} |
| 1723 |
return t.separatorLen |
| 1724 |
} |
| 1725 |
|
| 1726 |
// BorderLine for the input border resolves to a single line on the side |
| 1727 |
// facing the list section |
| 1728 |
func resolveInputBorderShape(layout layoutType, shape tui.BorderShape) tui.BorderShape { |
| 1729 |
if shape != tui.BorderLine { |
| 1730 |
return shape |
| 1731 |
} |
| 1732 |
if layout == layoutReverse { |
| 1733 |
return tui.BorderBottom |
| 1734 |
} |
| 1735 |
return tui.BorderTop |
| 1736 |
} |
| 1737 |
|
| 1738 |
// Whether the input border draws a line on the side facing the list section |
| 1739 |
func inputBorderFacesList(layout layoutType, shape tui.BorderShape) bool { |
| 1740 |
shape = resolveInputBorderShape(layout, shape) |
| 1741 |
if layout == layoutReverse { |
| 1742 |
return shape.HasBottom() |
| 1743 |
} |
| 1744 |
return shape.HasTop() |
| 1745 |
} |
| 1746 |
|
| 1747 |
// Whether a border line is already drawn between the info line and the |
| 1748 |
// section next to it on the list side, making the default horizontal |
| 1749 |
// separator redundant |
| 1750 |
func (t *Terminal) separatedByBorder() bool { |
| 1751 |
// The input border itself draws a line on the side facing the list section |
| 1752 |
if inputBorderFacesList(t.layout, t.inputBorderShape) { |
| 1753 |
return true |
| 1754 |
} |
| 1755 |
// A preview window at 'next' position sits right next to the input |
| 1756 |
// section, in front of the sections handled below |
| 1757 |
anyNext := false |
| 1758 |
for po := &t.previewOpts; po != nil; po = po.alternative { |
| 1759 |
if po.position == posNext { |
| 1760 |
anyNext = true |
| 1761 |
break |
| 1762 |
} |
| 1763 |
} |
| 1764 |
if anyNext && t.hasPreviewer() { |
| 1765 |
// The separator is hidden only when every spec in the threshold chain |
| 1766 |
// displays a preview window at 'next' position with a border line |
| 1767 |
// facing the input section. We cannot single out the active spec; |
| 1768 |
// which one is active depends on the terminal size, and the |
| 1769 |
// resolution (computePreviewSize in resizeWindows) itself consults |
| 1770 |
// noSeparatorLine. When not every spec qualifies, err on the side of |
| 1771 |
// showing the separator. |
| 1772 |
if len(t.previewOpts.command) == 0 { |
| 1773 |
// No preview command, so no preview window is normally shown, but |
| 1774 |
// the preview(...) action can still display one at any time |
| 1775 |
return false |
| 1776 |
} |
| 1777 |
// NOTE: resizeWindows can clear 'hidden' mid-layout when the |
| 1778 |
// preview(...) action forces the window, so the frame being laid out |
| 1779 |
// can briefly disagree with this decision until the next relayout |
| 1780 |
for po := &t.previewOpts; po != nil; po = po.alternative { |
| 1781 |
if po.position != posNext || po.hidden || po.size.size == 0 || !t.borderFacingInput(po.Border(t.layout)) { |
| 1782 |
return false |
| 1783 |
} |
| 1784 |
} |
| 1785 |
return true |
| 1786 |
} |
| 1787 |
hasHeaderLinesWindow, headerLinesShape := t.determineHeaderLinesShape() |
| 1788 |
hasHeaderWindow := t.hasHeaderWindow() |
| 1789 |
// Mirror of hasInputWindow in resizeWindows; a 'next' preview position |
| 1790 |
// gives the input section its own window even when no preview window is |
| 1791 |
// shown. A 'next' spec here implies there is no previewer (the block |
| 1792 |
// above returns otherwise), and without a previewer the position is |
| 1793 |
// resolved from the first spec alone, so a 'next' in a threshold |
| 1794 |
// alternative does not count. |
| 1795 |
hasInputWindow := t.previewOpts.position == posNext || t.inputBorderShape.Visible() || hasHeaderWindow || hasHeaderLinesWindow |
| 1796 |
if !hasInputWindow { |
| 1797 |
// The input section is embedded in the list window and no border |
| 1798 |
// separates the two |
| 1799 |
return false |
| 1800 |
} |
| 1801 |
|
| 1802 |
// The input section has its own window. Determine which section it is |
| 1803 |
// facing, and check if the border of that section draws a line toward it. |
| 1804 |
// NOTE: hasHeaderWindow can be true with no header content when the input |
| 1805 |
// border is visible (see Terminal.hasHeaderWindow). An empty header window |
| 1806 |
// takes no space, so it cannot be the facing section. |
| 1807 |
hasHeaderSection := hasHeaderWindow && t.visibleHeaderLines() > 0 |
| 1808 |
if hasHeaderSection && !t.headerFirst && t.headerBorderShape != tui.BorderInline { |
| 1809 |
// Header section is facing the input section. An inline header is |
| 1810 |
// excluded; it is drawn inside the list border and is covered by the |
| 1811 |
// branches below. |
| 1812 |
return t.borderFacingInput(t.headerBorderShape) |
| 1813 |
} |
| 1814 |
// Header lines section is facing the input section, except in |
| 1815 |
// reverse-list layout where it is on the other side of the list section, |
| 1816 |
// or with --header-first and no header section where it is moved past |
| 1817 |
// the input section |
| 1818 |
if hasHeaderLinesWindow && t.layout != layoutReverseList && (hasHeaderWindow || !t.headerFirst) { |
| 1819 |
return t.borderFacingInput(headerLinesShape) |
| 1820 |
} |
| 1821 |
// The input section sits right next to the list section |
| 1822 |
return t.borderFacingInput(t.listBorderShape) |
| 1823 |
} |
| 1824 |
|
| 1825 |
// Whether the border of the section next to the input section on the list |
| 1826 |
// side draws a horizontal line facing the info line |
| 1827 |
func (t *Terminal) borderFacingInput(shape tui.BorderShape) bool { |
| 1828 |
if shape == tui.BorderInline { |
| 1829 |
// Embedded between the horizontal lines of the list border |
| 1830 |
return true |
| 1831 |
} |
| 1832 |
if t.layout == layoutReverse { |
| 1833 |
return shape.HasTop() |
| 1834 |
} |
| 1835 |
return shape.HasBottom() |
| 1836 |
} |
| 1837 |
|
| 1838 |
func getScrollbar(perLine int, total int, height int, offset int) (int, int) { |
| 1839 |
if total == 0 || total*perLine <= height { |
| 1840 |
return 0, 0 |
| 1841 |
} |
| 1842 |
barLength := max(1, height*height/(total*perLine)) |
| 1843 |
var barStart int |
| 1844 |
if total == height { |
| 1845 |
barStart = 0 |
| 1846 |
} else { |
| 1847 |
barStart = min(height-barLength, (height*perLine-barLength)*offset/(total*perLine-height)) |
| 1848 |
} |
| 1849 |
return barLength, barStart |
| 1850 |
} |
| 1851 |
|
| 1852 |
func (t *Terminal) barCol() int { |
| 1853 |
if len(t.scrollbar) == 0 && !t.listBorderShape.HasRight() && !t.borderShape.HasRight() && !t.hasPreviewWindowOnRight() { |
| 1854 |
return 0 |
| 1855 |
} |
| 1856 |
return 1 |
| 1857 |
} |
| 1858 |
|
| 1859 |
func (t *Terminal) wrapCols() int { |
| 1860 |
if !t.wrap { |
| 1861 |
return 0 // No wrap |
| 1862 |
} |
| 1863 |
return max(t.window.Width()-(t.pointerLen+t.markerLen+t.barCol()), 1) |
| 1864 |
} |
| 1865 |
|
| 1866 |
func (t *Terminal) clearNumLinesCache() { |
| 1867 |
t.numLinesCache = make(map[int32]numLinesCacheValue) |
| 1868 |
} |
| 1869 |
|
| 1870 |
// Number of lines the item takes including the gap |
| 1871 |
func (t *Terminal) numItemLines(item *Item, atMost int) (int, bool) { |
| 1872 |
var numLines int |
| 1873 |
if !t.wrap && !t.multiLine { |
| 1874 |
numLines = 1 + t.gap |
| 1875 |
return numLines, numLines > atMost |
| 1876 |
} |
| 1877 |
if cached, prs := t.numLinesCache[item.Index()]; prs { |
| 1878 |
// Can we use this cache? Let's be conservative. |
| 1879 |
if cached.atMost <= atMost { |
| 1880 |
return cached.numLines, false |
| 1881 |
} |
| 1882 |
} |
| 1883 |
var overflow bool |
| 1884 |
if !t.wrap && t.multiLine { |
| 1885 |
numLines, overflow = item.text.NumLines(atMost) |
| 1886 |
} else { |
| 1887 |
var lines [][]rune |
| 1888 |
lines, overflow = item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop, t.wrapWord) |
| 1889 |
numLines = len(lines) |
| 1890 |
} |
| 1891 |
numLines += t.gap |
| 1892 |
if !overflow { |
| 1893 |
t.numLinesCache[item.Index()] = numLinesCacheValue{atMost, numLines} |
| 1894 |
} |
| 1895 |
return numLines, overflow || numLines > atMost |
| 1896 |
} |
| 1897 |
|
| 1898 |
func (t *Terminal) itemLines(item *Item, atMost int) ([][]rune, bool) { |
| 1899 |
if !t.wrap && !t.multiLine { |
| 1900 |
text := make([]rune, item.text.Length()) |
| 1901 |
copy(text, item.text.ToRunes()) |
| 1902 |
return [][]rune{text}, false |
| 1903 |
} |
| 1904 |
return item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop, t.wrapWord) |
| 1905 |
} |
| 1906 |
|
| 1907 |
// Estimate the average number of lines per item. Instead of going through all |
| 1908 |
// items, we only check a few items around the current cursor position. |
| 1909 |
func (t *Terminal) avgNumLines() int { |
| 1910 |
if !t.wrap && !t.multiLine { |
| 1911 |
return 1 |
| 1912 |
} |
| 1913 |
|
| 1914 |
maxItems := t.maxItems() |
| 1915 |
numLines := 0 |
| 1916 |
count := 0 |
| 1917 |
total := t.merger.Length() |
| 1918 |
offset := max(0, min(t.offset, total-maxItems-1)) |
| 1919 |
for idx := 0; idx < maxItems && idx+offset < total; idx++ { |
| 1920 |
result := t.merger.Get(idx + offset) |
| 1921 |
lines, _ := t.numItemLines(result.item, maxItems) |
| 1922 |
numLines += lines |
| 1923 |
count++ |
| 1924 |
} |
| 1925 |
if count == 0 { |
| 1926 |
return 1 |
| 1927 |
} |
| 1928 |
return numLines / count |
| 1929 |
} |
| 1930 |
|
| 1931 |
func (t *Terminal) getScrollbar() (int, int) { |
| 1932 |
return getScrollbar(t.avgNumLines(), t.merger.Length(), t.maxItems(), t.offset) |
| 1933 |
} |
| 1934 |
|
| 1935 |
// Input returns current query string |
| 1936 |
func (t *Terminal) Input() (bool, []rune) { |
| 1937 |
t.mutex.Lock() |
| 1938 |
defer t.mutex.Unlock() |
| 1939 |
paused := t.paused |
| 1940 |
src := t.input |
| 1941 |
if t.inputOverride != nil { |
| 1942 |
paused = false |
| 1943 |
src = *t.inputOverride |
| 1944 |
} |
| 1945 |
return paused, copySlice(src) |
| 1946 |
} |
| 1947 |
|
| 1948 |
// PauseRendering blocks the terminal from reading items. |
| 1949 |
// Must be paired with ResumeRendering. |
| 1950 |
func (t *Terminal) PauseRendering() { |
| 1951 |
t.mutex.Lock() |
| 1952 |
} |
| 1953 |
|
| 1954 |
// ResumeRendering releases the lock acquired by PauseRendering. |
| 1955 |
func (t *Terminal) ResumeRendering() { |
| 1956 |
t.mutex.Unlock() |
| 1957 |
} |
| 1958 |
|
| 1959 |
// UpdateCount updates the count information |
| 1960 |
func (t *Terminal) UpdateCount(cnt int, final bool, failedCommand *string) { |
| 1961 |
t.mutex.Lock() |
| 1962 |
t.count = cnt |
| 1963 |
if t.hasLoadActions && t.reading && final { |
| 1964 |
t.triggerLoad = true |
| 1965 |
} |
| 1966 |
t.reading = !final |
| 1967 |
t.failed = failedCommand |
| 1968 |
suppressed := t.suppress |
| 1969 |
t.mutex.Unlock() |
| 1970 |
t.reqBox.Set(reqInfo, nil) |
| 1971 |
|
| 1972 |
// We want to defer activating the interface when --sync is used and any of |
| 1973 |
// start, load, or result events are bound |
| 1974 |
if suppressed && final && !t.deferActivation() { |
| 1975 |
t.reqBox.Set(reqActivate, nil) |
| 1976 |
} |
| 1977 |
} |
| 1978 |
|
| 1979 |
func (t *Terminal) changeHeader(header string) bool { |
| 1980 |
var lines []string |
| 1981 |
if len(header) > 0 { |
| 1982 |
lines = strings.Split(strings.TrimSuffix(header, "\n"), "\n") |
| 1983 |
} |
| 1984 |
needFullRedraw := len(t.header0) != len(lines) |
| 1985 |
t.header0 = lines |
| 1986 |
t.clickHeaderLine = 0 |
| 1987 |
t.clickHeaderColumn = 0 |
| 1988 |
return needFullRedraw |
| 1989 |
} |
| 1990 |
|
| 1991 |
func (t *Terminal) changeFooter(footer string) bool { |
| 1992 |
var lines []string |
| 1993 |
if len(footer) > 0 { |
| 1994 |
lines = strings.Split(strings.TrimSuffix(footer, "\n"), "\n") |
| 1995 |
} |
| 1996 |
needFullRedraw := len(t.footer) != len(lines) |
| 1997 |
t.footer = lines |
| 1998 |
t.clickFooterLine = 0 |
| 1999 |
t.clickFooterColumn = 0 |
| 2000 |
return needFullRedraw |
| 2001 |
} |
| 2002 |
|
| 2003 |
// UpdateHeader updates the header |
| 2004 |
func (t *Terminal) UpdateHeader(header []Item) { |
| 2005 |
t.mutex.Lock() |
| 2006 |
// Pad to t.headerLines so that click coordinate mapping works correctly |
| 2007 |
if len(header) < t.headerLines { |
| 2008 |
padded := make([]Item, t.headerLines) |
| 2009 |
copy(padded, header) |
| 2010 |
header = padded |
| 2011 |
} |
| 2012 |
t.header = header |
| 2013 |
t.mutex.Unlock() |
| 2014 |
t.reqBox.Set(reqHeader, nil) |
| 2015 |
} |
| 2016 |
|
| 2017 |
// UpdateProgress updates the search progress |
| 2018 |
func (t *Terminal) UpdateProgress(progress float32) { |
| 2019 |
t.mutex.Lock() |
| 2020 |
newProgress := int(progress * 100) |
| 2021 |
changed := t.progress != newProgress |
| 2022 |
t.progress = newProgress |
| 2023 |
t.mutex.Unlock() |
| 2024 |
|
| 2025 |
if changed { |
| 2026 |
t.reqBox.Set(reqInfo, nil) |
| 2027 |
} |
| 2028 |
} |
| 2029 |
|
| 2030 |
// UpdateList updates Merger to display the list |
| 2031 |
func (t *Terminal) UpdateList(result MatchResult) { |
| 2032 |
merger := result.merger |
| 2033 |
t.mutex.Lock() |
| 2034 |
waitWasBlocked := t.wait.blocked |
| 2035 |
wakeUp := false |
| 2036 |
if result.final() { |
| 2037 |
t.wait.searching = false |
| 2038 |
// If waiting, unblock so main loop can execute pending actions. |
| 2039 |
// Note: any final result unblocks the wait, not just the one for the |
| 2040 |
// search that armed it. Back-to-back searches (--listen, bg-transform |
| 2041 |
// callbacks, reload+wait) can therefore unblock early and run the |
| 2042 |
// pending actions on the previous result set. Accepted; a per-search |
| 2043 |
// generation token through the matcher isn't worth the complexity. |
| 2044 |
if t.wait.blocked { |
| 2045 |
t.unblockWait() |
| 2046 |
wakeUp = len(t.wait.pending) > 0 |
| 2047 |
} |
| 2048 |
} |
| 2049 |
prevIndex := minItem.Index() |
| 2050 |
newRevision := merger.Revision() |
| 2051 |
if t.revision.compatible(newRevision) && t.track != trackDisabled { |
| 2052 |
if t.merger.Length() > 0 { |
| 2053 |
prevIndex = t.currentIndex() |
| 2054 |
} else if merger.Length() > 0 { |
| 2055 |
prevIndex = merger.First().item.Index() |
| 2056 |
} |
| 2057 |
} |
| 2058 |
if t.targetIndex != minItem.Index() { |
| 2059 |
prevIndex = t.targetIndex |
| 2060 |
t.targetIndex = minItem.Index() |
| 2061 |
} |
| 2062 |
if result.final() { |
| 2063 |
t.progress = 100 |
| 2064 |
} |
| 2065 |
t.merger = merger |
| 2066 |
t.resultMerger = merger |
| 2067 |
t.passMerger = result.passMerger |
| 2068 |
if t.raw { |
| 2069 |
t.merger = result.passMerger |
| 2070 |
t.matchMap = t.resultMerger.ToMap() |
| 2071 |
} else { |
| 2072 |
t.merger = result.merger |
| 2073 |
t.matchMap = make(map[int32]Result) |
| 2074 |
} |
| 2075 |
if t.revision != newRevision { |
| 2076 |
if !t.revision.compatible(newRevision) { |
| 2077 |
// Reloaded: capture selection keys for restoration, then clear (reload-sync only) |
| 2078 |
if t.trackSync && len(t.idNth) > 0 && t.multi > 0 && len(t.selected) > 0 { |
| 2079 |
t.pendingSelections = make(map[string]selectedItem, len(t.selected)) |
| 2080 |
for _, sel := range t.selected { |
| 2081 |
key := t.trackKeyFor(sel.item, t.idNth) |
| 2082 |
t.pendingSelections[key] = sel |
| 2083 |
} |
| 2084 |
} |
| 2085 |
t.selected = make(map[int32]selectedItem) |
| 2086 |
t.clearNumLinesCache() |
| 2087 |
} else { |
| 2088 |
// Trimmed by --tail: filter selection by index |
| 2089 |
filtered := make(map[int32]selectedItem) |
| 2090 |
minIndex := merger.minIndex |
| 2091 |
maxIndex := merger.maxIndex |
| 2092 |
for k, v := range t.selected { |
| 2093 |
var included bool |
| 2094 |
if maxIndex > minIndex { |
| 2095 |
included = k >= minIndex && k < maxIndex |
| 2096 |
} else if maxIndex < minIndex { // int32 overflow [==> <==] |
| 2097 |
included = k >= minIndex || k < maxIndex |
| 2098 |
} |
| 2099 |
if included { |
| 2100 |
filtered[k] = v |
| 2101 |
} |
| 2102 |
} |
| 2103 |
t.selected = filtered |
| 2104 |
} |
| 2105 |
t.revision = newRevision |
| 2106 |
t.version++ |
| 2107 |
|
| 2108 |
// Filter out selections that no longer match after with-nth change. |
| 2109 |
// Must be inside the revision check so we don't consume the flag |
| 2110 |
// on a stale EvtSearchFin from a previous search. |
| 2111 |
if t.filterSelection && t.multi > 0 && len(t.selected) > 0 { |
| 2112 |
matchMap := t.resultMerger.ToMap() |
| 2113 |
filtered := make(map[int32]selectedItem) |
| 2114 |
for k, v := range t.selected { |
| 2115 |
if _, matched := matchMap[k]; matched { |
| 2116 |
filtered[k] = v |
| 2117 |
} |
| 2118 |
} |
| 2119 |
t.selected = filtered |
| 2120 |
} |
| 2121 |
t.filterSelection = false |
| 2122 |
} |
| 2123 |
if t.triggerLoad { |
| 2124 |
t.triggerLoad = false |
| 2125 |
t.pendingReqList = true |
| 2126 |
t.eventChan <- tui.Load.AsEvent() |
| 2127 |
} |
| 2128 |
// Search for the tracked item by nth key |
| 2129 |
// - reload (async): search eagerly, unblock as soon as match is found |
| 2130 |
// - reload-sync: wait until stream is complete before searching |
| 2131 |
trackWasBlocked := t.trackBlocked |
| 2132 |
if len(t.trackKey) > 0 && (!t.trackSync || !t.reading) { |
| 2133 |
found := false |
| 2134 |
for i := 0; i < t.merger.Length(); i++ { |
| 2135 |
item := t.merger.Get(i).item |
| 2136 |
idx := item.Index() |
| 2137 |
match, ok := t.trackKeyCache[idx] |
| 2138 |
if !ok { |
| 2139 |
match = t.trackKeyFor(item, t.idNth) == t.trackKey |
| 2140 |
t.trackKeyCache[idx] = match |
| 2141 |
} |
| 2142 |
if match { |
| 2143 |
t.cy = i |
| 2144 |
if t.track.Current() { |
| 2145 |
t.track.index = idx |
| 2146 |
} |
| 2147 |
found = true |
| 2148 |
break |
| 2149 |
} |
| 2150 |
} |
| 2151 |
if found || !t.reading { |
| 2152 |
t.unblockTrack() |
| 2153 |
} |
| 2154 |
} else if prevIndex >= 0 { |
| 2155 |
pos := t.cy - t.offset |
| 2156 |
count := t.merger.Length() |
| 2157 |
i := t.merger.FindIndex(prevIndex) |
| 2158 |
if i >= 0 { |
| 2159 |
t.cy = i |
| 2160 |
t.offset = t.cy - pos |
| 2161 |
} else if t.track.Current() { |
| 2162 |
t.track = trackDisabled |
| 2163 |
t.cy = pos |
| 2164 |
t.offset = 0 |
| 2165 |
} else if t.cy > count { |
| 2166 |
// Try to keep the vertical position when the list shrinks |
| 2167 |
t.cy = count - min(count, t.maxItems()) + pos |
| 2168 |
} |
| 2169 |
} |
| 2170 |
// Restore selections by id-nth key after reload completes |
| 2171 |
if !t.reading && t.pendingSelections != nil { |
| 2172 |
for i := 0; i < t.merger.Length() && len(t.pendingSelections) > 0; i++ { |
| 2173 |
item := t.merger.Get(i).item |
| 2174 |
key := t.trackKeyFor(item, t.idNth) |
| 2175 |
if sel, found := t.pendingSelections[key]; found { |
| 2176 |
t.selected[item.Index()] = selectedItem{sel.at, item} |
| 2177 |
delete(t.pendingSelections, key) |
| 2178 |
} |
| 2179 |
} |
| 2180 |
t.pendingSelections = nil |
| 2181 |
} |
| 2182 |
needActivation := false |
| 2183 |
if !t.reading { |
| 2184 |
switch t.resultMerger.Length() { |
| 2185 |
case 0: |
| 2186 |
zero := tui.Zero.AsEvent() |
| 2187 |
if _, prs := t.keymap[zero]; prs { |
| 2188 |
t.pendingReqList = true |
| 2189 |
t.eventChan <- zero |
| 2190 |
} |
| 2191 |
// --sync, only 'focus' is bound, but no items to focus |
| 2192 |
needActivation = t.suppress && !t.hasResultActions && !t.hasLoadActions && t.hasFocusActions |
| 2193 |
case 1: |
| 2194 |
one := tui.One.AsEvent() |
| 2195 |
if _, prs := t.keymap[one]; prs { |
| 2196 |
t.pendingReqList = true |
| 2197 |
t.eventChan <- one |
| 2198 |
} |
| 2199 |
} |
| 2200 |
} |
| 2201 |
if t.hasResultActions { |
| 2202 |
result := tui.Result.AsEvent() |
| 2203 |
if _, prs := t.keymap[result]; prs { |
| 2204 |
t.pendingReqList = true |
| 2205 |
t.eventChan <- result |
| 2206 |
} |
| 2207 |
if !t.reading { |
| 2208 |
resultFinal := tui.ResultFinal.AsEvent() |
| 2209 |
if _, prs := t.keymap[resultFinal]; prs { |
| 2210 |
t.pendingReqList = true |
| 2211 |
t.eventChan <- resultFinal |
| 2212 |
} |
| 2213 |
} |
| 2214 |
} |
| 2215 |
updateList := !t.trackBlocked && !t.pendingReqList |
| 2216 |
updatePrompt := (trackWasBlocked && !t.trackBlocked) || (waitWasBlocked && !t.wait.blocked) |
| 2217 |
t.mutex.Unlock() |
| 2218 |
|
| 2219 |
// Wake up the main loop to execute pending actions after wait unblocks. |
| 2220 |
// Send from a goroutine; UpdateList runs inside the event box callback, |
| 2221 |
// and an inline send on a full channel would deadlock with the main loop |
| 2222 |
// blocking on eventBox.Set while trying to drain the channel. |
| 2223 |
if wakeUp { |
| 2224 |
go func() { |
| 2225 |
t.serverInputChan <- []*action{{t: actIgnore}} |
| 2226 |
}() |
| 2227 |
} |
| 2228 |
|
| 2229 |
t.reqBox.Set(reqInfo, nil) |
| 2230 |
if updateList { |
| 2231 |
t.reqBox.Set(reqList, nil) |
| 2232 |
} |
| 2233 |
if updatePrompt { |
| 2234 |
t.reqBox.Set(reqPrompt, nil) |
| 2235 |
} |
| 2236 |
if needActivation { |
| 2237 |
t.reqBox.Set(reqActivate, nil) |
| 2238 |
} |
| 2239 |
} |
| 2240 |
|
| 2241 |
func (t *Terminal) output() bool { |
| 2242 |
if t.printQuery { |
| 2243 |
t.printer(string(t.input)) |
| 2244 |
} |
| 2245 |
if len(t.expect) > 0 { |
| 2246 |
t.printer(t.pressed) |
| 2247 |
} |
| 2248 |
for _, s := range t.printQueue { |
| 2249 |
t.printer(s) |
| 2250 |
} |
| 2251 |
transform := func(item *Item) string { |
| 2252 |
return item.AsString(t.ansi) |
| 2253 |
} |
| 2254 |
if t.acceptNth != nil { |
| 2255 |
transform = func(item *Item) string { |
| 2256 |
return item.acceptNth(t.ansi, t.delimiter, t.acceptNth) |
| 2257 |
} |
| 2258 |
} |
| 2259 |
found := len(t.selected) > 0 |
| 2260 |
if !found { |
| 2261 |
current := t.currentItem() |
| 2262 |
if current != nil { |
| 2263 |
t.printer(transform(current)) |
| 2264 |
found = true |
| 2265 |
} |
| 2266 |
} else { |
| 2267 |
for _, sel := range t.sortSelected() { |
| 2268 |
t.printer(transform(sel.item)) |
| 2269 |
} |
| 2270 |
} |
| 2271 |
return found |
| 2272 |
} |
| 2273 |
|
| 2274 |
func (t *Terminal) sortSelected() []selectedItem { |
| 2275 |
sels := make([]selectedItem, 0, len(t.selected)) |
| 2276 |
for _, sel := range t.selected { |
| 2277 |
sels = append(sels, sel) |
| 2278 |
} |
| 2279 |
sort.Sort(byTimeOrder(sels)) |
| 2280 |
return sels |
| 2281 |
} |
| 2282 |
|
| 2283 |
func (t *Terminal) displayWidth(runes []rune) int { |
| 2284 |
width, _ := util.RunesWidth(runes, 0, t.tabstop, math.MaxInt32) |
| 2285 |
return width |
| 2286 |
} |
| 2287 |
|
| 2288 |
func (t *Terminal) displayWidthWithPrefix(str string, prefixWidth int) int { |
| 2289 |
width, _ := util.RunesWidth([]rune(str), prefixWidth, t.tabstop, math.MaxInt32) |
| 2290 |
return width |
| 2291 |
} |
| 2292 |
|
| 2293 |
// displayWidthWithoutEscapes is displayWidthWithPrefix for a string that may |
| 2294 |
// still carry pass-throughs and ANSI codes, neither of which take any column. |
| 2295 |
func (t *Terminal) displayWidthWithoutEscapes(str string, prefixWidth int) int { |
| 2296 |
_, text := extractPassThroughs(str) |
| 2297 |
stripped, _, _ := extractColor(text, nil, nil) |
| 2298 |
return t.displayWidthWithPrefix(stripped, prefixWidth) |
| 2299 |
} |
| 2300 |
|
| 2301 |
const ( |
| 2302 |
minWidth = 4 |
| 2303 |
minHeight = 3 |
| 2304 |
) |
| 2305 |
|
| 2306 |
func calculateSize(base int, size sizeSpec, occupied int, minSize int) int { |
| 2307 |
max := base - occupied |
| 2308 |
if max < minSize { |
| 2309 |
max = minSize |
| 2310 |
} |
| 2311 |
if size.percent { |
| 2312 |
return util.Constrain(int(float64(base)*0.01*size.size), minSize, max) |
| 2313 |
} |
| 2314 |
return util.Constrain(int(size.size)+minSize-1, minSize, max) |
| 2315 |
} |
| 2316 |
|
| 2317 |
func (t *Terminal) minPreviewSize(opts *previewOpts) (int, int) { |
| 2318 |
border := opts.Border(t.layout) |
| 2319 |
minPreviewWidth := 1 + borderColumns(border, t.borderWidth) |
| 2320 |
minPreviewHeight := 1 + borderLines(border) |
| 2321 |
|
| 2322 |
switch opts.position { |
| 2323 |
case posLeft, posRight: |
| 2324 |
if len(t.scrollbar) > 0 && !border.HasRight() { |
| 2325 |
// Need a column to show scrollbar |
| 2326 |
minPreviewWidth++ |
| 2327 |
} |
| 2328 |
} |
| 2329 |
|
| 2330 |
return minPreviewWidth, minPreviewHeight |
| 2331 |
} |
| 2332 |
|
| 2333 |
func (t *Terminal) adjustMarginAndPadding() (int, int, [4]int, [4]int) { |
| 2334 |
screenWidth := t.tui.MaxX() |
| 2335 |
screenHeight := t.tui.MaxY() |
| 2336 |
marginInt := [4]int{} // TRBL |
| 2337 |
paddingInt := [4]int{} // TRBL |
| 2338 |
sizeSpecToInt := func(index int, spec sizeSpec) int { |
| 2339 |
if spec.percent { |
| 2340 |
var max float64 |
| 2341 |
if index%2 == 0 { |
| 2342 |
max = float64(screenHeight) |
| 2343 |
} else { |
| 2344 |
max = float64(screenWidth) |
| 2345 |
} |
| 2346 |
return int(max * spec.size * 0.01) |
| 2347 |
} |
| 2348 |
return int(spec.size) |
| 2349 |
} |
| 2350 |
for idx, sizeSpec := range t.padding { |
| 2351 |
paddingInt[idx] = sizeSpecToInt(idx, sizeSpec) |
| 2352 |
} |
| 2353 |
|
| 2354 |
bw := t.borderWidth |
| 2355 |
extraMargin := [4]int{} // TRBL |
| 2356 |
for idx, sizeSpec := range t.margin { |
| 2357 |
switch t.borderShape { |
| 2358 |
case tui.BorderHorizontal: |
| 2359 |
extraMargin[idx] += 1 - idx%2 |
| 2360 |
case tui.BorderVertical: |
| 2361 |
extraMargin[idx] += (1 + bw) * (idx % 2) |
| 2362 |
case tui.BorderTop: |
| 2363 |
if idx == 0 { |
| 2364 |
extraMargin[idx]++ |
| 2365 |
} |
| 2366 |
case tui.BorderRight: |
| 2367 |
if idx == 1 { |
| 2368 |
extraMargin[idx] += 1 + bw |
| 2369 |
} |
| 2370 |
case tui.BorderBottom: |
| 2371 |
if idx == 2 { |
| 2372 |
extraMargin[idx]++ |
| 2373 |
} |
| 2374 |
case tui.BorderLeft: |
| 2375 |
if idx == 3 { |
| 2376 |
extraMargin[idx] += 1 + bw |
| 2377 |
} |
| 2378 |
case tui.BorderRounded, tui.BorderSharp, tui.BorderBold, tui.BorderBlock, tui.BorderThinBlock, tui.BorderDouble, tui.BorderDashed: |
| 2379 |
extraMargin[idx] += 1 + bw*(idx%2) |
| 2380 |
} |
| 2381 |
marginInt[idx] = sizeSpecToInt(idx, sizeSpec) + extraMargin[idx] |
| 2382 |
} |
| 2383 |
|
| 2384 |
adjust := func(idx1 int, idx2 int, maximum int, minimum int) { |
| 2385 |
if minimum > maximum { |
| 2386 |
minimum = maximum |
| 2387 |
} |
| 2388 |
margin := marginInt[idx1] + marginInt[idx2] + paddingInt[idx1] + paddingInt[idx2] |
| 2389 |
if maximum-margin < minimum { |
| 2390 |
desired := maximum - minimum |
| 2391 |
paddingInt[idx1] = desired * paddingInt[idx1] / margin |
| 2392 |
paddingInt[idx2] = desired * paddingInt[idx2] / margin |
| 2393 |
marginInt[idx1] = max(extraMargin[idx1], desired*marginInt[idx1]/margin) |
| 2394 |
marginInt[idx2] = max(extraMargin[idx2], desired*marginInt[idx2]/margin) |
| 2395 |
} |
| 2396 |
} |
| 2397 |
|
| 2398 |
minAreaWidth := minWidth |
| 2399 |
minAreaHeight := minHeight |
| 2400 |
if t.inputless { |
| 2401 |
minAreaHeight-- |
| 2402 |
} |
| 2403 |
if t.noSeparatorLine() { |
| 2404 |
minAreaHeight-- |
| 2405 |
} |
| 2406 |
if t.needPreviewWindow() { |
| 2407 |
minPreviewWidth, minPreviewHeight := t.minPreviewSize(t.activePreviewOpts) |
| 2408 |
switch t.activePreviewOpts.position { |
| 2409 |
case posUp, posDown, posNext: |
| 2410 |
minAreaHeight += minPreviewHeight |
| 2411 |
minAreaWidth = max(minPreviewWidth, minAreaWidth) |
| 2412 |
case posLeft, posRight: |
| 2413 |
minAreaWidth += minPreviewWidth |
| 2414 |
minAreaHeight = max(minPreviewHeight, minAreaHeight) |
| 2415 |
} |
| 2416 |
} |
| 2417 |
adjust(1, 3, screenWidth, minAreaWidth) |
| 2418 |
adjust(0, 2, screenHeight, minAreaHeight) |
| 2419 |
|
| 2420 |
return screenWidth, screenHeight, marginInt, paddingInt |
| 2421 |
} |
| 2422 |
|
| 2423 |
func (t *Terminal) forceRerenderList() { |
| 2424 |
t.prevLines = make([]itemLine, len(t.prevLines)) |
| 2425 |
} |
| 2426 |
|
| 2427 |
func (t *Terminal) hasHeaderWindow() bool { |
| 2428 |
if !t.headerVisible { |
| 2429 |
return false |
| 2430 |
} |
| 2431 |
if t.hasHeaderLinesWindow() { |
| 2432 |
return len(t.header0) > 0 |
| 2433 |
} |
| 2434 |
if t.headerBorderShape.Visible() || t.headerFirst { |
| 2435 |
return len(t.header0)+t.headerLines > 0 |
| 2436 |
} |
| 2437 |
return t.inputBorderShape.Visible() |
| 2438 |
} |
| 2439 |
|
| 2440 |
func (t *Terminal) hasHeaderLinesWindow() bool { |
| 2441 |
w, _ := t.determineHeaderLinesShape() |
| 2442 |
return w |
| 2443 |
} |
| 2444 |
|
| 2445 |
func (t *Terminal) determineHeaderLinesShape() (bool, tui.BorderShape) { |
| 2446 |
if !t.headerVisible || t.headerLines == 0 { |
| 2447 |
return false, tui.BorderNone |
| 2448 |
} |
| 2449 |
|
| 2450 |
// --header-lines-border is set |
| 2451 |
if t.headerLinesShape != tui.BorderUndefined { |
| 2452 |
return true, t.headerLinesShape |
| 2453 |
} |
| 2454 |
|
| 2455 |
// --header-lines-border is not set, determine if we should use |
| 2456 |
// the style of --header-border |
| 2457 |
shape := tui.BorderNone |
| 2458 |
if len(t.header0) == 0 { |
| 2459 |
shape = t.headerBorderShape |
| 2460 |
} |
| 2461 |
if shape == tui.BorderNone { |
| 2462 |
shape = tui.BorderPhantom |
| 2463 |
} |
| 2464 |
|
| 2465 |
// --layout reverse-list is set |
| 2466 |
if t.layout == layoutReverseList { |
| 2467 |
return true, shape |
| 2468 |
} |
| 2469 |
|
| 2470 |
// Use header window instead |
| 2471 |
if len(t.header0) == 0 { |
| 2472 |
if t.headerFirst && shape == tui.BorderPhantom { |
| 2473 |
return true, shape |
| 2474 |
} |
| 2475 |
return false, t.headerBorderShape |
| 2476 |
} |
| 2477 |
|
| 2478 |
// We have both types of headers, and we want to separate the two |
| 2479 |
if t.headerFirst { |
| 2480 |
return true, shape |
| 2481 |
} |
| 2482 |
|
| 2483 |
return false, tui.BorderNone |
| 2484 |
} |
| 2485 |
|
| 2486 |
// Inline sections live inside wborder rather than consuming shift/shrink/availableLines. |
| 2487 |
type inlineRole int |
| 2488 |
|
| 2489 |
const ( |
| 2490 |
inlineRoleHeader inlineRole = iota |
| 2491 |
inlineRoleHeaderLines |
| 2492 |
inlineRoleFooter |
| 2493 |
) |
| 2494 |
|
| 2495 |
type inlineSlot struct { |
| 2496 |
role inlineRole |
| 2497 |
windowType tui.WindowType |
| 2498 |
contentLines int // 0 when out of budget: a ghost placeholder is created so |
| 2499 |
// t.headerWindow / t.footerWindow stay non-nil but no frame is painted. |
| 2500 |
label labelPrinter |
| 2501 |
labelOpts labelOpts |
| 2502 |
labelLen int |
| 2503 |
} |
| 2504 |
|
| 2505 |
// inlineMetaFor returns (onTop: top stack vs bottom; windowType; isInner: |
| 2506 |
// adjacent to list content) for the given inline role, derived from the layout. |
| 2507 |
// Header is outer when paired with header-lines; header-lines is always inner; |
| 2508 |
// footer is inner except in reverseList where it sits outside header-lines. |
| 2509 |
func (t *Terminal) inlineMetaFor(role inlineRole) (onTop bool, windowType tui.WindowType, isInner bool) { |
| 2510 |
switch role { |
| 2511 |
case inlineRoleHeader: |
| 2512 |
return t.layout == layoutReverse, tui.WindowHeader, false |
| 2513 |
case inlineRoleHeaderLines: |
| 2514 |
return t.layout != layoutDefault, tui.WindowHeader, true |
| 2515 |
case inlineRoleFooter: |
| 2516 |
return t.layout != layoutReverse, tui.WindowFooter, t.layout != layoutReverseList |
| 2517 |
} |
| 2518 |
return false, tui.WindowBase, false |
| 2519 |
} |
| 2520 |
|
| 2521 |
func (t *Terminal) placeInlineSection(win tui.Window, role inlineRole) { |
| 2522 |
switch role { |
| 2523 |
case inlineRoleHeader: |
| 2524 |
t.headerWindow = win |
| 2525 |
case inlineRoleHeaderLines: |
| 2526 |
t.headerLinesWindow = win |
| 2527 |
case inlineRoleFooter: |
| 2528 |
t.footerWindow = win |
| 2529 |
} |
| 2530 |
} |
| 2531 |
|
| 2532 |
// placeInlineStack walks `slots` in outer-to-inner order. Only the outermost |
| 2533 |
// slot (index 0) claims the adjacent wborder edge; later slots paint side-only |
| 2534 |
// frames so the T-junction separator lands between sections. |
| 2535 |
func (t *Terminal) placeInlineStack(slots []inlineSlot, startRow int, onTop bool) { |
| 2536 |
firstEdge := tui.SectionEdgeTop |
| 2537 |
if !onTop { |
| 2538 |
firstEdge = tui.SectionEdgeBottom |
| 2539 |
} |
| 2540 |
noBorder := tui.MakeBorderStyle(tui.BorderNone, t.unicode) |
| 2541 |
subLeft := t.window.Left() |
| 2542 |
subWidth := t.window.Width() |
| 2543 |
cursor := startRow |
| 2544 |
for i, s := range slots { |
| 2545 |
var windowTop, sepRow int |
| 2546 |
if onTop { |
| 2547 |
windowTop = cursor |
| 2548 |
sepRow = cursor + s.contentLines - t.wborder.Top() |
| 2549 |
} else { |
| 2550 |
windowTop = cursor - s.contentLines + 1 |
| 2551 |
sepRow = windowTop - 1 - t.wborder.Top() |
| 2552 |
} |
| 2553 |
// 0-height placeholder keeps t.headerWindow / t.footerWindow non-nil. |
| 2554 |
win := t.tui.NewWindow(windowTop, subLeft, subWidth, s.contentLines, s.windowType, noBorder, true) |
| 2555 |
t.placeInlineSection(win, s.role) |
| 2556 |
if s.contentLines == 0 { |
| 2557 |
continue |
| 2558 |
} |
| 2559 |
secTop := windowTop - t.wborder.Top() |
| 2560 |
secBottom := secTop + s.contentLines - 1 |
| 2561 |
edge := tui.SectionEdgeNone |
| 2562 |
if i == 0 { |
| 2563 |
edge = firstEdge |
| 2564 |
} |
| 2565 |
t.wborder.PaintSectionFrame(secTop, secBottom, s.windowType, edge) |
| 2566 |
// useBottom=onTop so the separator always hugs the list (inner side). |
| 2567 |
// Matters for thinblock/block where top != bottom char. |
| 2568 |
t.wborder.DrawHSeparator(sepRow, s.windowType, onTop) |
| 2569 |
t.printLabelAt(t.wborder, s.label, s.labelOpts, s.labelLen, sepRow) |
| 2570 |
if onTop { |
| 2571 |
cursor += s.contentLines + 1 |
| 2572 |
} else { |
| 2573 |
cursor -= s.contentLines + 1 |
| 2574 |
} |
| 2575 |
} |
| 2576 |
} |
| 2577 |
|
| 2578 |
func (t *Terminal) resizeWindows(forcePreview bool, redrawBorder bool) { |
| 2579 |
t.clearNumLinesCache() |
| 2580 |
t.forcePreview = forcePreview |
| 2581 |
screenWidth, screenHeight, marginInt, paddingInt := t.adjustMarginAndPadding() |
| 2582 |
width := screenWidth - marginInt[1] - marginInt[3] |
| 2583 |
height := screenHeight - marginInt[0] - marginInt[2] |
| 2584 |
|
| 2585 |
t.prevLines = make([]itemLine, max(1, screenHeight)) |
| 2586 |
if t.border != nil && redrawBorder { |
| 2587 |
t.border = nil |
| 2588 |
} |
| 2589 |
if t.window != nil { |
| 2590 |
t.window = nil |
| 2591 |
} |
| 2592 |
if t.wborder != nil { |
| 2593 |
t.wborder = nil |
| 2594 |
} |
| 2595 |
if t.headerWindow != nil { |
| 2596 |
t.headerWindow = nil |
| 2597 |
} |
| 2598 |
if t.headerBorder != nil { |
| 2599 |
t.headerBorder = nil |
| 2600 |
} |
| 2601 |
if t.footerWindow != nil { |
| 2602 |
t.footerWindow = nil |
| 2603 |
} |
| 2604 |
if t.footerBorder != nil { |
| 2605 |
t.footerBorder = nil |
| 2606 |
} |
| 2607 |
if t.headerLinesWindow != nil { |
| 2608 |
t.headerLinesWindow = nil |
| 2609 |
} |
| 2610 |
if t.headerLinesBorder != nil { |
| 2611 |
t.headerLinesBorder = nil |
| 2612 |
} |
| 2613 |
if t.inputWindow != nil { |
| 2614 |
t.inputWindow = nil |
| 2615 |
} |
| 2616 |
if t.inputBorder != nil { |
| 2617 |
t.inputBorder = nil |
| 2618 |
} |
| 2619 |
if t.pborder != nil { |
| 2620 |
t.pborder = nil |
| 2621 |
} |
| 2622 |
hadPreviewWindow := t.hasPreviewWindow() |
| 2623 |
if hadPreviewWindow { |
| 2624 |
t.pwindow = nil |
| 2625 |
} |
| 2626 |
// Reset preview version so that full redraw occurs |
| 2627 |
t.previewed.version = 0 |
| 2628 |
|
| 2629 |
bw := t.borderWidth |
| 2630 |
offsets := [4]int{} // TRWH |
| 2631 |
if t.borderShape.HasTop() { |
| 2632 |
offsets[0] -= 1 |
| 2633 |
offsets[3] += 1 |
| 2634 |
} |
| 2635 |
if t.borderShape.HasRight() { |
| 2636 |
offsets[2] += 1 + bw |
| 2637 |
} |
| 2638 |
if t.borderShape.HasBottom() { |
| 2639 |
offsets[3] += 1 |
| 2640 |
} |
| 2641 |
if t.borderShape.HasLeft() { |
| 2642 |
offsets[1] -= 1 + bw |
| 2643 |
offsets[2] += 1 + bw |
| 2644 |
} |
| 2645 |
if t.border == nil && t.borderShape.Visible() { |
| 2646 |
t.border = t.tui.NewWindow( |
| 2647 |
marginInt[0]+offsets[0], marginInt[3]+offsets[1], width+offsets[2], height+offsets[3], |
| 2648 |
tui.WindowBase, tui.MakeBorderStyle(t.borderShape, t.unicode), true) |
| 2649 |
} |
| 2650 |
|
| 2651 |
// Add padding to margin |
| 2652 |
for idx, val := range paddingInt { |
| 2653 |
marginInt[idx] += val |
| 2654 |
} |
| 2655 |
width -= paddingInt[1] + paddingInt[3] |
| 2656 |
height -= paddingInt[0] + paddingInt[2] |
| 2657 |
|
| 2658 |
// Adjust position and size of the list window if input border is set |
| 2659 |
inputBorderHeight := 0 |
| 2660 |
availableLines := height |
| 2661 |
|
| 2662 |
shift := 0 |
| 2663 |
shrink := 0 |
| 2664 |
hasHeaderWindow := t.hasHeaderWindow() |
| 2665 |
hasFooterWindow := len(t.footer) > 0 |
| 2666 |
hasHeaderLinesWindow, headerLinesShape := t.determineHeaderLinesShape() |
| 2667 |
// computePreviewSize returns the size resizePreviewWindows will compute |
| 2668 |
// for opts and the minimum size for that axis: height/minPreviewHeight |
| 2669 |
// for vertical positions, width/minPreviewWidth for horizontal. |
| 2670 |
computePreviewSize := func(opts *previewOpts) (int, int) { |
| 2671 |
minPreviewWidth, minPreviewHeight := t.minPreviewSize(opts) |
| 2672 |
switch opts.position { |
| 2673 |
case posUp, posDown, posNext: |
| 2674 |
minWindowHeight := minHeight |
| 2675 |
if t.inputless { |
| 2676 |
minWindowHeight-- |
| 2677 |
} |
| 2678 |
if t.noSeparatorLine() { |
| 2679 |
minWindowHeight-- |
| 2680 |
} |
| 2681 |
return calculateSize(height, opts.size, minWindowHeight, minPreviewHeight), minPreviewHeight |
| 2682 |
case posLeft, posRight: |
| 2683 |
minListWidth := minWidth |
| 2684 |
if t.listBorderShape.HasLeft() { |
| 2685 |
minListWidth += 2 |
| 2686 |
} |
| 2687 |
if t.listBorderShape.HasRight() { |
| 2688 |
minListWidth++ |
| 2689 |
} |
| 2690 |
return calculateSize(width, opts.size, minListWidth, minPreviewWidth), minPreviewWidth |
| 2691 |
} |
| 2692 |
return 0, 0 |
| 2693 |
} |
| 2694 |
// Walk the threshold chain to determine the previewOpts that |
| 2695 |
// resizePreviewWindows will actually settle on. We need this here |
| 2696 |
// because hasInputWindow and the availableLines adjustment below run |
| 2697 |
// before resizePreviewWindows, and t.activePreviewOpts still holds the |
| 2698 |
// previous frame's resolution. |
| 2699 |
effectivePreviewOpts := &t.previewOpts |
| 2700 |
if t.needPreviewWindow() { |
| 2701 |
opts := &t.previewOpts |
| 2702 |
for { |
| 2703 |
if opts.size.size == 0 || opts.threshold <= 0 || opts.alternative == nil { |
| 2704 |
break |
| 2705 |
} |
| 2706 |
if actual, _ := computePreviewSize(opts); actual >= opts.threshold { |
| 2707 |
break |
| 2708 |
} |
| 2709 |
opts = opts.alternative |
| 2710 |
if opts.hidden { |
| 2711 |
break |
| 2712 |
} |
| 2713 |
} |
| 2714 |
effectivePreviewOpts = opts |
| 2715 |
} |
| 2716 |
hasInputWindow := !t.inputless && (t.inputBorderShape.Visible() || hasHeaderWindow || hasHeaderLinesWindow || effectivePreviewOpts.position == posNext) |
| 2717 |
inputWindowHeight := 2 |
| 2718 |
if t.noSeparatorLine() { |
| 2719 |
inputWindowHeight-- |
| 2720 |
} |
| 2721 |
if hasInputWindow { |
| 2722 |
inputBorderHeight = util.Constrain(borderLines(t.inputBorderShape)+inputWindowHeight, 0, availableLines) |
| 2723 |
if t.layout == layoutReverse { |
| 2724 |
shift = inputBorderHeight |
| 2725 |
shrink = inputBorderHeight |
| 2726 |
} else { |
| 2727 |
shrink = inputBorderHeight |
| 2728 |
} |
| 2729 |
availableLines -= inputBorderHeight |
| 2730 |
} else if !t.inputless { |
| 2731 |
availableLines -= inputWindowHeight |
| 2732 |
} |
| 2733 |
|
| 2734 |
// FIXME: Needed? |
| 2735 |
if t.needPreviewWindow() { |
| 2736 |
switch effectivePreviewOpts.position { |
| 2737 |
case posUp, posDown, posNext: |
| 2738 |
_, minPreviewHeight := t.minPreviewSize(effectivePreviewOpts) |
| 2739 |
availableLines -= minPreviewHeight |
| 2740 |
} |
| 2741 |
} |
| 2742 |
|
| 2743 |
// Slices are ordered outer-to-inner: index 0 touches wborder's edge. |
| 2744 |
var inlineTop []inlineSlot |
| 2745 |
var inlineBottom []inlineSlot |
| 2746 |
|
| 2747 |
// Caps contentLines against remaining wborder space. Oversized requests (e.g. a |
| 2748 |
// huge --header-lines) become 0-height placeholders rather than pushing the list |
| 2749 |
// window to negative height. |
| 2750 |
addInline := func(contentLines int, role inlineRole) { |
| 2751 |
onTop, windowType, isInner := t.inlineMetaFor(role) |
| 2752 |
used := 0 |
| 2753 |
for _, s := range inlineTop { |
| 2754 |
if s.contentLines > 0 { |
| 2755 |
used += s.contentLines + 1 |
| 2756 |
} |
| 2757 |
} |
| 2758 |
for _, s := range inlineBottom { |
| 2759 |
if s.contentLines > 0 { |
| 2760 |
used += s.contentLines + 1 |
| 2761 |
} |
| 2762 |
} |
| 2763 |
remaining := availableLines - borderLines(t.listBorderShape) - used - 1 |
| 2764 |
if remaining < 2 { |
| 2765 |
contentLines = 0 |
| 2766 |
} else { |
| 2767 |
contentLines = util.Constrain(contentLines, 1, remaining-1) |
| 2768 |
} |
| 2769 |
slot := inlineSlot{role: role, windowType: windowType, contentLines: contentLines} |
| 2770 |
switch role { |
| 2771 |
case inlineRoleHeader: |
| 2772 |
slot.label, slot.labelOpts, slot.labelLen = t.headerLabel, t.headerLabelOpts, t.headerLabelLen |
| 2773 |
case inlineRoleFooter: |
| 2774 |
slot.label, slot.labelOpts, slot.labelLen = t.footerLabel, t.footerLabelOpts, t.footerLabelLen |
| 2775 |
} |
| 2776 |
target := &inlineTop |
| 2777 |
if !onTop { |
| 2778 |
target = &inlineBottom |
| 2779 |
} |
| 2780 |
if isInner { |
| 2781 |
*target = append(*target, slot) |
| 2782 |
} else { |
| 2783 |
*target = append([]inlineSlot{slot}, *target...) |
| 2784 |
} |
| 2785 |
} |
| 2786 |
|
| 2787 |
// Adjust position and size of the list window if header border is set |
| 2788 |
headerBorderHeight := 0 |
| 2789 |
if hasHeaderWindow { |
| 2790 |
headerWindowHeight := t.visibleHeaderLines() |
| 2791 |
if hasHeaderLinesWindow { |
| 2792 |
headerWindowHeight -= t.headerLines |
| 2793 |
} |
| 2794 |
if t.headerBorderShape == tui.BorderInline { |
| 2795 |
addInline(headerWindowHeight, inlineRoleHeader) |
| 2796 |
} else { |
| 2797 |
headerBorderHeight = util.Constrain(borderLines(t.headerBorderShape)+headerWindowHeight, 0, availableLines) |
| 2798 |
if t.layout == layoutReverse { |
| 2799 |
shift += headerBorderHeight |
| 2800 |
shrink += headerBorderHeight |
| 2801 |
} else { |
| 2802 |
shrink += headerBorderHeight |
| 2803 |
} |
| 2804 |
availableLines -= headerBorderHeight |
| 2805 |
} |
| 2806 |
} |
| 2807 |
|
| 2808 |
headerLinesHeight := 0 |
| 2809 |
if hasHeaderLinesWindow { |
| 2810 |
if headerLinesShape == tui.BorderInline { |
| 2811 |
addInline(t.headerLines, inlineRoleHeaderLines) |
| 2812 |
} else { |
| 2813 |
headerLinesHeight = util.Constrain(borderLines(headerLinesShape)+t.headerLines, 0, availableLines) |
| 2814 |
if t.layout != layoutDefault { |
| 2815 |
shift += headerLinesHeight |
| 2816 |
shrink += headerLinesHeight |
| 2817 |
} else { |
| 2818 |
shrink += headerLinesHeight |
| 2819 |
} |
| 2820 |
availableLines -= headerLinesHeight |
| 2821 |
} |
| 2822 |
} |
| 2823 |
|
| 2824 |
footerBorderHeight := 0 |
| 2825 |
if hasFooterWindow { |
| 2826 |
if t.footerBorderShape == tui.BorderInline { |
| 2827 |
addInline(len(t.footer), inlineRoleFooter) |
| 2828 |
} else { |
| 2829 |
// Footer lines should not take all available lines |
| 2830 |
footerBorderHeight = util.Constrain(borderLines(t.footerBorderShape)+len(t.footer), 0, availableLines) |
| 2831 |
shrink += footerBorderHeight |
| 2832 |
if t.layout != layoutReverse { |
| 2833 |
shift += footerBorderHeight |
| 2834 |
} |
| 2835 |
availableLines -= footerBorderHeight |
| 2836 |
} |
| 2837 |
} |
| 2838 |
|
| 2839 |
inlineTopLines := 0 |
| 2840 |
for _, s := range inlineTop { |
| 2841 |
if s.contentLines > 0 { |
| 2842 |
inlineTopLines += s.contentLines + 1 |
| 2843 |
} |
| 2844 |
} |
| 2845 |
inlineBottomLines := 0 |
| 2846 |
for _, s := range inlineBottom { |
| 2847 |
if s.contentLines > 0 { |
| 2848 |
inlineBottomLines += s.contentLines + 1 |
| 2849 |
} |
| 2850 |
} |
| 2851 |
|
| 2852 |
// Set up list border |
| 2853 |
hasListBorder := t.listBorderShape.Visible() |
| 2854 |
innerWidth := width |
| 2855 |
innerHeight := height |
| 2856 |
innerMarginInt := marginInt |
| 2857 |
innerBorderFn := func(top int, left int, width int, height int) { |
| 2858 |
if hasListBorder { |
| 2859 |
t.wborder = t.tui.NewWindow( |
| 2860 |
top+shift, left, width, height-shrink, tui.WindowList, tui.MakeBorderStyle(t.listBorderShape, t.unicode), false) |
| 2861 |
} |
| 2862 |
} |
| 2863 |
if hasListBorder { |
| 2864 |
if t.listBorderShape.HasTop() { |
| 2865 |
innerHeight-- |
| 2866 |
innerMarginInt[0]++ |
| 2867 |
} |
| 2868 |
if t.listBorderShape.HasBottom() { |
| 2869 |
innerHeight-- |
| 2870 |
} |
| 2871 |
if t.listBorderShape.HasLeft() { |
| 2872 |
innerWidth -= 2 |
| 2873 |
innerMarginInt[3] += 2 |
| 2874 |
} |
| 2875 |
if t.listBorderShape.HasRight() { |
| 2876 |
innerWidth-- |
| 2877 |
} |
| 2878 |
} |
| 2879 |
|
| 2880 |
t.areaLines = height |
| 2881 |
t.areaColumns = width |
| 2882 |
|
| 2883 |
// If none of the inner borders has the right side, but the outer border does, increase the list width by 1 column |
| 2884 |
listStickToRight := t.borderShape.HasRight() && !t.listBorderShape.HasRight() && !t.inputBorderShape.HasRight() && |
| 2885 |
(!t.headerVisible || !t.headerBorderShape.HasRight() || t.visibleHeaderLines() == 0) |
| 2886 |
|
| 2887 |
// Set up preview window |
| 2888 |
noBorder := tui.MakeBorderStyle(tui.BorderNone, t.unicode) |
| 2889 |
cleanLeft := []int{} |
| 2890 |
// previewNextSize is pheight when the preview is placed adjacent to |
| 2891 |
// the input (position == "next"); inputBorderTop() reads it through the |
| 2892 |
// closure to push input past the preview band. |
| 2893 |
previewNextSize := 0 |
| 2894 |
// inputBorderTop returns the canvas Y at which the input border window |
| 2895 |
// should be placed. It depends on wborder/t.window (set by the preview |
| 2896 |
// case), the layout, --header-first, and previewNextSize (set when |
| 2897 |
// posNext is active). Used both for placing the preview adjacent to |
| 2898 |
// input and later for placing the input window itself. |
| 2899 |
inputBorderTop := func() int { |
| 2900 |
w := t.wborder |
| 2901 |
if w == nil { |
| 2902 |
w = t.window |
| 2903 |
} |
| 2904 |
hasSeparateHeader := hasHeaderWindow && t.headerBorderShape != tui.BorderInline |
| 2905 |
hasSeparateHeaderLines := hasHeaderLinesWindow && headerLinesShape != tui.BorderInline |
| 2906 |
if (hasSeparateHeader || hasSeparateHeaderLines) && t.headerFirst { |
| 2907 |
switch t.layout { |
| 2908 |
case layoutDefault: |
| 2909 |
btop := w.Top() + w.Height() + previewNextSize |
| 2910 |
if hasHeaderWindow && hasHeaderLinesWindow { |
| 2911 |
btop += headerLinesHeight |
| 2912 |
} |
| 2913 |
return btop |
| 2914 |
case layoutReverse: |
| 2915 |
btop := w.Top() - inputBorderHeight - previewNextSize |
| 2916 |
if hasHeaderWindow && hasHeaderLinesWindow { |
| 2917 |
btop -= headerLinesHeight |
| 2918 |
} |
| 2919 |
return btop |
| 2920 |
case layoutReverseList: |
| 2921 |
return w.Top() + w.Height() + previewNextSize |
| 2922 |
} |
| 2923 |
} |
| 2924 |
switch t.layout { |
| 2925 |
case layoutDefault: |
| 2926 |
return w.Top() + w.Height() + headerBorderHeight + headerLinesHeight + previewNextSize |
| 2927 |
case layoutReverse: |
| 2928 |
return w.Top() - shrink + footerBorderHeight - previewNextSize |
| 2929 |
case layoutReverseList: |
| 2930 |
return w.Top() + w.Height() + headerBorderHeight + previewNextSize |
| 2931 |
} |
| 2932 |
return 0 |
| 2933 |
} |
| 2934 |
if forcePreview || t.needPreviewWindow() { |
| 2935 |
var resizePreviewWindows func(previewOpts *previewOpts) |
| 2936 |
resizePreviewWindows = func(previewOpts *previewOpts) { |
| 2937 |
t.activePreviewOpts = previewOpts |
| 2938 |
if previewOpts.size.size == 0 { |
| 2939 |
return |
| 2940 |
} |
| 2941 |
hasThreshold := previewOpts.threshold > 0 && previewOpts.alternative != nil |
| 2942 |
createPreviewWindow := func(y int, x int, w int, h int) { |
| 2943 |
pwidth := w |
| 2944 |
pheight := h |
| 2945 |
shape := previewOpts.Border(t.layout) |
| 2946 |
previewBorder := tui.MakeBorderStyle(shape, t.unicode) |
| 2947 |
t.pborder = t.tui.NewWindow(y, x, w, h, tui.WindowPreview, previewBorder, false) |
| 2948 |
pwidth -= borderColumns(shape, bw) |
| 2949 |
pheight -= borderLines(shape) |
| 2950 |
if shape.HasLeft() { |
| 2951 |
x += 1 + bw |
| 2952 |
} |
| 2953 |
if shape.HasTop() { |
| 2954 |
y += 1 |
| 2955 |
} |
| 2956 |
if len(t.scrollbar) > 0 && !shape.HasRight() { |
| 2957 |
// Need a column to show scrollbar |
| 2958 |
pwidth -= 1 |
| 2959 |
} |
| 2960 |
t.pwindow = t.tui.NewWindow(y, x, pwidth, pheight, tui.WindowPreview, noBorder, true) |
| 2961 |
t.pwindow.SetWrapSign(t.previewWrapSign, t.previewWrapSignWidth) |
| 2962 |
if !hadPreviewWindow { |
| 2963 |
t.pwindow.Erase() |
| 2964 |
} |
| 2965 |
} |
| 2966 |
// Shared boilerplate for vertical positions (posUp/posDown/posNext): |
| 2967 |
// compute pheight, apply the threshold alternative, honor hidden, |
| 2968 |
// and update listStickToRight. Returns (pheight, true) when the |
| 2969 |
// caller should return early. |
| 2970 |
computeVerticalSize := func() (int, bool) { |
| 2971 |
pheight, minPreviewHeight := computePreviewSize(previewOpts) |
| 2972 |
if hasThreshold && pheight < previewOpts.threshold { |
| 2973 |
t.activePreviewOpts = previewOpts.alternative |
| 2974 |
if forcePreview { |
| 2975 |
previewOpts.alternative.hidden = false |
| 2976 |
} |
| 2977 |
if !previewOpts.alternative.hidden { |
| 2978 |
resizePreviewWindows(previewOpts.alternative) |
| 2979 |
} |
| 2980 |
return 0, true |
| 2981 |
} |
| 2982 |
if forcePreview { |
| 2983 |
previewOpts.hidden = false |
| 2984 |
} |
| 2985 |
if previewOpts.hidden { |
| 2986 |
return 0, true |
| 2987 |
} |
| 2988 |
listStickToRight = listStickToRight && !previewOpts.Border(t.layout).HasRight() |
| 2989 |
if listStickToRight { |
| 2990 |
innerWidth++ |
| 2991 |
width++ |
| 2992 |
} |
| 2993 |
return util.Constrain(pheight, minPreviewHeight, availableLines), false |
| 2994 |
} |
| 2995 |
switch previewOpts.position { |
| 2996 |
case posUp, posDown: |
| 2997 |
pheight, done := computeVerticalSize() |
| 2998 |
if done { |
| 2999 |
return |
| 3000 |
} |
| 3001 |
|
| 3002 |
if previewOpts.position == posUp { |
| 3003 |
innerBorderFn(marginInt[0]+pheight, marginInt[3], width, height-pheight) |
| 3004 |
t.window = t.tui.NewWindow( |
| 3005 |
innerMarginInt[0]+pheight+shift+inlineTopLines, innerMarginInt[3], innerWidth, innerHeight-pheight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3006 |
createPreviewWindow(marginInt[0], marginInt[3], width, pheight) |
| 3007 |
} else { |
| 3008 |
innerBorderFn(marginInt[0], marginInt[3], width, height-pheight) |
| 3009 |
t.window = t.tui.NewWindow( |
| 3010 |
innerMarginInt[0]+shift+inlineTopLines, innerMarginInt[3], innerWidth, innerHeight-pheight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3011 |
createPreviewWindow(marginInt[0]+height-pheight, marginInt[3], width, pheight) |
| 3012 |
} |
| 3013 |
case posNext: |
| 3014 |
pheight, done := computeVerticalSize() |
| 3015 |
if done { |
| 3016 |
return |
| 3017 |
} |
| 3018 |
previewNextSize = pheight |
| 3019 |
|
| 3020 |
if t.layout == layoutReverse { |
| 3021 |
// [(header)][input][preview]([header])[list]: reuse posUp's |
| 3022 |
// wborder/list math; input is pulled back up by pheight in |
| 3023 |
// its positioning. Preview sits directly below input. |
| 3024 |
innerBorderFn(marginInt[0]+pheight, marginInt[3], width, height-pheight) |
| 3025 |
t.window = t.tui.NewWindow( |
| 3026 |
innerMarginInt[0]+pheight+shift+inlineTopLines, innerMarginInt[3], innerWidth, innerHeight-pheight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3027 |
createPreviewWindow(inputBorderTop()+inputBorderHeight, marginInt[3], width, pheight) |
| 3028 |
} else { |
| 3029 |
// [list]([header])[preview][input][(header)]: reuse posDown's |
| 3030 |
// wborder/list math; input is pushed down by pheight in its |
| 3031 |
// positioning. Preview sits directly above input. |
| 3032 |
innerBorderFn(marginInt[0], marginInt[3], width, height-pheight) |
| 3033 |
t.window = t.tui.NewWindow( |
| 3034 |
innerMarginInt[0]+shift+inlineTopLines, innerMarginInt[3], innerWidth, innerHeight-pheight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3035 |
createPreviewWindow(inputBorderTop()-pheight, marginInt[3], width, pheight) |
| 3036 |
} |
| 3037 |
case posLeft, posRight: |
| 3038 |
pwidth, _ := computePreviewSize(previewOpts) |
| 3039 |
if hasThreshold && pwidth < previewOpts.threshold { |
| 3040 |
t.activePreviewOpts = previewOpts.alternative |
| 3041 |
if forcePreview { |
| 3042 |
previewOpts.alternative.hidden = false |
| 3043 |
} |
| 3044 |
if !previewOpts.alternative.hidden { |
| 3045 |
resizePreviewWindows(previewOpts.alternative) |
| 3046 |
} |
| 3047 |
return |
| 3048 |
} |
| 3049 |
if forcePreview { |
| 3050 |
previewOpts.hidden = false |
| 3051 |
} |
| 3052 |
if previewOpts.hidden { |
| 3053 |
return |
| 3054 |
} |
| 3055 |
if previewOpts.position == posLeft { |
| 3056 |
// Put scrollbar closer to the right border for consistent look |
| 3057 |
if t.borderShape.HasRight() && !hasListBorder { |
| 3058 |
innerWidth++ |
| 3059 |
} |
| 3060 |
// Add a 1-column margin between the preview window and the main window |
| 3061 |
m := 0 |
| 3062 |
if !hasListBorder { |
| 3063 |
m = 1 |
| 3064 |
} |
| 3065 |
t.window = t.tui.NewWindow( |
| 3066 |
innerMarginInt[0]+shift+inlineTopLines, innerMarginInt[3]+pwidth+m, innerWidth-pwidth-m, innerHeight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3067 |
|
| 3068 |
// Clear characters on the margin |
| 3069 |
// fzf --bind 'space:toggle-preview' --preview ':' --preview-window left,1,border-none --footer-border --footer f --header h --header-border |
| 3070 |
if !previewOpts.Border(t.layout).HasRight() { |
| 3071 |
cleanLeft = append(cleanLeft, -2) |
| 3072 |
} |
| 3073 |
// fzf --bind 'space:toggle-preview' --preview ':' --preview-window left,1 --footer-border --footer f --header h --header-border |
| 3074 |
if !hasListBorder { |
| 3075 |
cleanLeft = append(cleanLeft, -1) |
| 3076 |
} |
| 3077 |
|
| 3078 |
innerBorderFn(marginInt[0], marginInt[3]+pwidth, width-pwidth, height) |
| 3079 |
createPreviewWindow(marginInt[0], marginInt[3], pwidth, height) |
| 3080 |
} else { |
| 3081 |
// NOTE: Relaxed condition for the following cases |
| 3082 |
// fzf --preview 'seq 500' --preview-window border-left --border |
| 3083 |
// fzf --preview 'seq 500' --preview-window border-left --border --list-border |
| 3084 |
// fzf --preview 'seq 500' --preview-window border-left --border --input-border |
| 3085 |
listStickToRight = t.borderShape.HasRight() && !previewOpts.Border(t.layout).HasRight() |
| 3086 |
if listStickToRight { |
| 3087 |
innerWidth++ |
| 3088 |
width++ |
| 3089 |
} |
| 3090 |
innerBorderFn(marginInt[0], marginInt[3], width-pwidth, height) |
| 3091 |
t.window = t.tui.NewWindow( |
| 3092 |
innerMarginInt[0]+shift+inlineTopLines, innerMarginInt[3], innerWidth-pwidth, innerHeight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3093 |
x := marginInt[3] + width - pwidth |
| 3094 |
createPreviewWindow(marginInt[0], x, pwidth, height) |
| 3095 |
} |
| 3096 |
} |
| 3097 |
} |
| 3098 |
resizePreviewWindows(&t.previewOpts) |
| 3099 |
|
| 3100 |
if t.borderShape.HasRight() && !listStickToRight { |
| 3101 |
// Need to clear the extra margin between the borders |
| 3102 |
// fzf --preview 'seq 1000' --preview-window border-left --bind space:change-preview-window:border-rounded --border vertical |
| 3103 |
// fzf --preview 'seq 1000' --preview-window up,hidden --bind space:toggle-preview --border vertical |
| 3104 |
y := 0 |
| 3105 |
if t.borderShape.HasTop() { |
| 3106 |
y++ |
| 3107 |
} |
| 3108 |
maxY := t.border.Height() |
| 3109 |
if t.borderShape.HasBottom() { |
| 3110 |
maxY-- |
| 3111 |
} |
| 3112 |
for ; y < maxY; y++ { |
| 3113 |
t.border.Move(y, t.border.Width()-2) |
| 3114 |
t.border.Print(" ") |
| 3115 |
} |
| 3116 |
} |
| 3117 |
} else { |
| 3118 |
t.activePreviewOpts = &t.previewOpts |
| 3119 |
} |
| 3120 |
|
| 3121 |
// Without preview window |
| 3122 |
if t.window == nil { |
| 3123 |
if listStickToRight { |
| 3124 |
// Put scrollbar closer to the right border for consistent look |
| 3125 |
innerWidth++ |
| 3126 |
width++ |
| 3127 |
} |
| 3128 |
innerBorderFn(marginInt[0], marginInt[3], width, height) |
| 3129 |
t.window = t.tui.NewWindow( |
| 3130 |
innerMarginInt[0]+shift+inlineTopLines, |
| 3131 |
innerMarginInt[3], |
| 3132 |
innerWidth, |
| 3133 |
innerHeight-shrink-inlineTopLines-inlineBottomLines, tui.WindowList, noBorder, true) |
| 3134 |
} |
| 3135 |
|
| 3136 |
if len(inlineTop)+len(inlineBottom) > 0 && t.wborder != nil { |
| 3137 |
t.placeInlineStack(inlineTop, t.window.Top()-inlineTopLines, true) |
| 3138 |
t.placeInlineStack(inlineBottom, t.window.Top()+t.window.Height()+inlineBottomLines-1, false) |
| 3139 |
} |
| 3140 |
|
| 3141 |
if len(t.scrollbar) == 0 { |
| 3142 |
for y := 0; y < t.window.Height(); y++ { |
| 3143 |
t.window.Move(y, t.window.Width()-1) |
| 3144 |
t.window.Print(" ") |
| 3145 |
} |
| 3146 |
} |
| 3147 |
|
| 3148 |
createInnerWindow := func(b tui.Window, shape tui.BorderShape, windowType tui.WindowType, shift int) tui.Window { |
| 3149 |
top := b.Top() |
| 3150 |
left := b.Left() + shift |
| 3151 |
if shape.HasTop() { |
| 3152 |
top++ |
| 3153 |
} |
| 3154 |
if shape.HasLeft() { |
| 3155 |
left += t.borderWidth + 1 |
| 3156 |
} |
| 3157 |
width := b.Width() - borderColumns(shape, t.borderWidth) - shift |
| 3158 |
if shape.HasRight() { |
| 3159 |
width++ |
| 3160 |
} |
| 3161 |
// Make sure that the width does not exceed the list width |
| 3162 |
width = min(t.window.Width()+t.headerIndentImpl(0, shape), width) |
| 3163 |
height := b.Height() - borderLines(shape) |
| 3164 |
return t.tui.NewWindow(top, left, width, height, windowType, noBorder, true) |
| 3165 |
} |
| 3166 |
|
| 3167 |
// Set up input border |
| 3168 |
w := t.wborder |
| 3169 |
if t.wborder == nil { |
| 3170 |
w = t.window |
| 3171 |
} |
| 3172 |
|
| 3173 |
if hasInputWindow { |
| 3174 |
btop := inputBorderTop() |
| 3175 |
shift := 0 |
| 3176 |
if !t.inputBorderShape.HasLeft() && t.listBorderShape.HasLeft() { |
| 3177 |
shift += t.borderWidth + 1 |
| 3178 |
} |
| 3179 |
t.inputBorder = t.tui.NewWindow( |
| 3180 |
btop, |
| 3181 |
w.Left(), |
| 3182 |
w.Width(), |
| 3183 |
inputBorderHeight, tui.WindowInput, tui.MakeBorderStyle(t.inputBorderShape, t.unicode), true) |
| 3184 |
if shift > 0 && !t.inputBorderShape.Visible() { |
| 3185 |
// Small box on the left to erase the residue |
| 3186 |
// e.g. |
| 3187 |
// fzf --list-border --header-border --bind 'space:change-header(hello),enter:change-header()' |
| 3188 |
t.tui.NewWindow(btop, w.Left(), shift, inputBorderHeight, tui.WindowInput, noBorder, false).Erase() |
| 3189 |
} |
| 3190 |
t.inputWindow = createInnerWindow(t.inputBorder, t.inputBorderShape, tui.WindowInput, shift) |
| 3191 |
} |
| 3192 |
|
| 3193 |
// Set up header border |
| 3194 |
if hasHeaderWindow && t.headerBorderShape != tui.BorderInline { |
| 3195 |
var btop int |
| 3196 |
if hasInputWindow && t.headerFirst { |
| 3197 |
if t.layout == layoutReverse { |
| 3198 |
btop = w.Top() - shrink + footerBorderHeight - previewNextSize |
| 3199 |
} else if t.layout == layoutReverseList { |
| 3200 |
btop = w.Top() + w.Height() + inputBorderHeight + previewNextSize |
| 3201 |
} else { |
| 3202 |
btop = w.Top() + w.Height() + inputBorderHeight + headerLinesHeight + previewNextSize |
| 3203 |
} |
| 3204 |
} else { |
| 3205 |
if t.layout == layoutReverse { |
| 3206 |
btop = w.Top() - headerBorderHeight - headerLinesHeight |
| 3207 |
} else if t.layout == layoutReverseList { |
| 3208 |
btop = w.Top() + w.Height() |
| 3209 |
} else { |
| 3210 |
btop = w.Top() + w.Height() + headerLinesHeight |
| 3211 |
} |
| 3212 |
} |
| 3213 |
t.headerBorder = t.tui.NewWindow( |
| 3214 |
btop, |
| 3215 |
w.Left(), |
| 3216 |
w.Width(), |
| 3217 |
headerBorderHeight, tui.WindowHeader, tui.MakeBorderStyle(t.headerBorderShape, t.unicode), true) |
| 3218 |
t.headerWindow = createInnerWindow(t.headerBorder, t.headerBorderShape, tui.WindowHeader, 0) |
| 3219 |
} |
| 3220 |
|
| 3221 |
// Set up header lines border |
| 3222 |
if hasHeaderLinesWindow && headerLinesShape != tui.BorderInline { |
| 3223 |
var btop int |
| 3224 |
// NOTE: We still have to handle --header-first here in case |
| 3225 |
// --header-lines-border is set. Can't we just use header window instead |
| 3226 |
// with the style? So we can display header label. |
| 3227 |
// fzf --header-lines 3 --header-label hello --header-border |
| 3228 |
// fzf --header-lines 3 --header-label hello --header-lines-border |
| 3229 |
headerFirst := t.headerFirst && len(t.header0) == 0 |
| 3230 |
|
| 3231 |
if headerFirst { |
| 3232 |
if t.layout == layoutDefault { |
| 3233 |
btop = w.Top() + w.Height() + inputBorderHeight + previewNextSize |
| 3234 |
} else if t.layout == layoutReverse { |
| 3235 |
btop = w.Top() - headerLinesHeight - inputBorderHeight |
| 3236 |
} else { |
| 3237 |
btop = w.Top() - headerLinesHeight |
| 3238 |
} |
| 3239 |
} else { |
| 3240 |
if t.layout != layoutDefault { |
| 3241 |
btop = w.Top() - headerLinesHeight |
| 3242 |
} else { |
| 3243 |
btop = w.Top() + w.Height() |
| 3244 |
} |
| 3245 |
} |
| 3246 |
t.headerLinesBorder = t.tui.NewWindow( |
| 3247 |
btop, |
| 3248 |
w.Left(), |
| 3249 |
w.Width(), |
| 3250 |
headerLinesHeight, tui.WindowHeader, tui.MakeBorderStyle(headerLinesShape, t.unicode), true) |
| 3251 |
t.headerLinesWindow = createInnerWindow(t.headerLinesBorder, headerLinesShape, tui.WindowHeader, 0) |
| 3252 |
} |
| 3253 |
|
| 3254 |
// Set up footer |
| 3255 |
if hasFooterWindow && t.footerBorderShape != tui.BorderInline { |
| 3256 |
var btop int |
| 3257 |
if t.layout == layoutReverse { |
| 3258 |
btop = w.Top() + w.Height() |
| 3259 |
} else if t.layout == layoutReverseList { |
| 3260 |
btop = w.Top() - footerBorderHeight - headerLinesHeight |
| 3261 |
} else { |
| 3262 |
btop = w.Top() - footerBorderHeight |
| 3263 |
} |
| 3264 |
t.footerBorder = t.tui.NewWindow( |
| 3265 |
btop, |
| 3266 |
w.Left(), |
| 3267 |
w.Width(), |
| 3268 |
footerBorderHeight, tui.WindowFooter, tui.MakeBorderStyle(t.footerBorderShape, t.unicode), true) |
| 3269 |
t.footerWindow = createInnerWindow(t.footerBorder, t.footerBorderShape, tui.WindowFooter, 0) |
| 3270 |
} |
| 3271 |
|
| 3272 |
for _, w := range []tui.Window{t.window, t.headerBorder, t.headerLinesBorder, t.footerBorder, t.inputBorder} { |
| 3273 |
if w == nil { |
| 3274 |
continue |
| 3275 |
} |
| 3276 |
|
| 3277 |
for y := 0; y < w.Height(); y++ { |
| 3278 |
for _, left := range cleanLeft { |
| 3279 |
w.Move(y, left) |
| 3280 |
w.Print(" ") |
| 3281 |
} |
| 3282 |
} |
| 3283 |
} |
| 3284 |
|
| 3285 |
// When the list label lands on an edge owned by an inline section, swap its bg |
| 3286 |
// so the label reads as part of that section's frame. Fg stays at list-label. |
| 3287 |
listLabel, listLabelLen := t.listLabel, t.listLabelLen |
| 3288 |
var adjacentSection *inlineSlot |
| 3289 |
if t.listLabelOpts.bottom && len(inlineBottom) > 0 { |
| 3290 |
adjacentSection = &inlineBottom[0] |
| 3291 |
} else if !t.listLabelOpts.bottom && len(inlineTop) > 0 { |
| 3292 |
adjacentSection = &inlineTop[0] |
| 3293 |
} |
| 3294 |
if adjacentSection != nil { |
| 3295 |
bg := tui.BorderColor(adjacentSection.windowType).Bg() |
| 3296 |
custom := tui.ColListLabel.WithBg(tui.ColorAttr{Color: bg, Attr: tui.AttrUndefined}) |
| 3297 |
listLabel, listLabelLen = t.ansiLabelPrinter(t.listLabelOpts.label, &custom, false) |
| 3298 |
} |
| 3299 |
t.printLabel(t.wborder, listLabel, t.listLabelOpts, listLabelLen, t.listBorderShape, false) |
| 3300 |
t.printLabel(t.border, t.borderLabel, t.borderLabelOpts, t.borderLabelLen, t.borderShape, false) |
| 3301 |
t.printLabel(t.pborder, t.previewLabel, t.previewLabelOpts, t.previewLabelLen, t.activePreviewOpts.Border(t.layout), false) |
| 3302 |
t.printLabel(t.inputBorder, t.inputLabel, t.inputLabelOpts, t.inputLabelLen, t.inputBorderShape, false) |
| 3303 |
t.printLabel(t.headerBorder, t.headerLabel, t.headerLabelOpts, t.headerLabelLen, t.headerBorderShape, false) |
| 3304 |
t.printLabel(t.footerBorder, t.footerLabel, t.footerLabelOpts, t.footerLabelLen, t.footerBorderShape, false) |
| 3305 |
} |
| 3306 |
|
| 3307 |
// printLabelAt positions and renders a label at the given row of `window`. Shared by |
| 3308 |
// printLabel (which computes row from the border shape) and the inline-section label |
| 3309 |
// code (which uses an explicit separator row). |
| 3310 |
func (t *Terminal) printLabelAt(window tui.Window, render labelPrinter, opts labelOpts, length int, row int) { |
| 3311 |
if window == nil || render == nil || window.Height() == 0 { |
| 3312 |
return |
| 3313 |
} |
| 3314 |
var col int |
| 3315 |
if opts.column == 0 { |
| 3316 |
col = max(0, (window.Width()-length)/2) |
| 3317 |
} else if opts.column < 0 { |
| 3318 |
col = max(0, window.Width()+opts.column+1-length) |
| 3319 |
} else { |
| 3320 |
col = min(opts.column-1, window.Width()-length) |
| 3321 |
} |
| 3322 |
window.Move(row, col) |
| 3323 |
render(window, window.Width()) |
| 3324 |
} |
| 3325 |
|
| 3326 |
func (t *Terminal) printLabel(window tui.Window, render labelPrinter, opts labelOpts, length int, borderShape tui.BorderShape, redrawBorder bool) { |
| 3327 |
if window == nil || window.Height() == 0 { |
| 3328 |
return |
| 3329 |
} |
| 3330 |
switch borderShape { |
| 3331 |
case tui.BorderHorizontal, tui.BorderTop, tui.BorderBottom, tui.BorderRounded, tui.BorderSharp, tui.BorderBold, tui.BorderBlock, tui.BorderThinBlock, tui.BorderDouble, tui.BorderDashed: |
| 3332 |
if redrawBorder { |
| 3333 |
window.DrawHBorder() |
| 3334 |
} |
| 3335 |
row := 0 |
| 3336 |
if borderShape == tui.BorderBottom || opts.bottom { |
| 3337 |
row = window.Height() - 1 |
| 3338 |
} |
| 3339 |
t.printLabelAt(window, render, opts, length, row) |
| 3340 |
} |
| 3341 |
} |
| 3342 |
|
| 3343 |
func (t *Terminal) move(y int, x int, clear bool) { |
| 3344 |
h := t.window.Height() |
| 3345 |
|
| 3346 |
switch t.layout { |
| 3347 |
case layoutDefault: |
| 3348 |
y = h - y - 1 |
| 3349 |
case layoutReverseList: |
| 3350 |
if !t.inListWindow() && t.window != t.headerLinesWindow { |
| 3351 |
// From bottom to top |
| 3352 |
y = h - y - 1 |
| 3353 |
} else { |
| 3354 |
/* |
| 3355 |
* List 1 |
| 3356 |
* List 2 |
| 3357 |
* Header 1 |
| 3358 |
* Header 2 |
| 3359 |
* Input 2 |
| 3360 |
* Input 1 |
| 3361 |
*/ |
| 3362 |
i := t.visibleInputLinesInList() |
| 3363 |
n := t.visibleHeaderLinesInList() |
| 3364 |
if i > 0 && y < i { |
| 3365 |
y = h - y - 1 |
| 3366 |
} else if n > 0 && y < i+n { |
| 3367 |
y = h - y - 1 |
| 3368 |
} else { |
| 3369 |
// Top to bottom |
| 3370 |
y -= n + i |
| 3371 |
} |
| 3372 |
} |
| 3373 |
} |
| 3374 |
|
| 3375 |
if clear { |
| 3376 |
t.window.MoveAndClear(y, x) |
| 3377 |
} else { |
| 3378 |
t.window.Move(y, x) |
| 3379 |
} |
| 3380 |
} |
| 3381 |
|
| 3382 |
func (t *Terminal) truncateQuery() { |
| 3383 |
// We're limiting the length of the query not to make fzf unresponsive when |
| 3384 |
// the user accidentally pastes a huge chunk of text. Therefore, we're not |
| 3385 |
// interested in the exact display width of the query. We just limit the |
| 3386 |
// number of runes. |
| 3387 |
t.input = t.input[:min(len(t.input), maxPatternLength)] |
| 3388 |
t.cx = util.Constrain(t.cx, 0, len(t.input)) |
| 3389 |
} |
| 3390 |
|
| 3391 |
func (t *Terminal) updatePromptOffset() ([]rune, []rune) { |
| 3392 |
w := t.window |
| 3393 |
if t.inputWindow != nil { |
| 3394 |
w = t.inputWindow |
| 3395 |
} |
| 3396 |
maxWidth := max(1, w.Width()-t.promptLen-1) |
| 3397 |
|
| 3398 |
_, overflow := t.trimLeft(t.input[:t.cx], maxWidth, 0) |
| 3399 |
minOffset := int(overflow) |
| 3400 |
maxOffset := minOffset + (maxWidth-max(0, maxWidth-t.cx))/2 |
| 3401 |
t.xoffset = util.Constrain(t.xoffset, minOffset, maxOffset) |
| 3402 |
before, _ := t.trimLeft(t.input[t.xoffset:t.cx], maxWidth, 0) |
| 3403 |
beforeLen := t.displayWidth(before) |
| 3404 |
after, _ := t.trimRight(t.input[t.cx:], maxWidth-beforeLen) |
| 3405 |
afterLen := t.displayWidth(after) |
| 3406 |
t.queryLen = [2]int{beforeLen, afterLen} |
| 3407 |
return before, after |
| 3408 |
} |
| 3409 |
|
| 3410 |
func (t *Terminal) placeCursor() { |
| 3411 |
if t.inputless { |
| 3412 |
return |
| 3413 |
} |
| 3414 |
x := t.promptLen + t.queryLen[0] |
| 3415 |
if t.inputWindow != nil { |
| 3416 |
y := t.inputWindow.Height() - 1 |
| 3417 |
if t.layout == layoutReverse { |
| 3418 |
y = 0 |
| 3419 |
} |
| 3420 |
x = min(x, t.inputWindow.Width()-1) |
| 3421 |
t.inputWindow.Move(y, x) |
| 3422 |
return |
| 3423 |
} |
| 3424 |
x = min(x, t.window.Width()-1) |
| 3425 |
t.move(0, x, false) |
| 3426 |
} |
| 3427 |
|
| 3428 |
func (t *Terminal) printPrompt() { |
| 3429 |
if t.inputless { |
| 3430 |
return |
| 3431 |
} |
| 3432 |
w := t.window |
| 3433 |
if t.inputWindow != nil { |
| 3434 |
w = t.inputWindow |
| 3435 |
} |
| 3436 |
if w.Height() == 0 { |
| 3437 |
return |
| 3438 |
} |
| 3439 |
t.prompt() |
| 3440 |
|
| 3441 |
before, after := t.updatePromptOffset() |
| 3442 |
if len(before) == 0 && len(after) == 0 && len(t.ghost) > 0 { |
| 3443 |
maxWidth := max(1, w.Width()-t.promptLen-1) |
| 3444 |
runes, _ := t.trimRight([]rune(t.ghost), maxWidth) |
| 3445 |
w.CPrint(tui.ColGhost, string(runes)) |
| 3446 |
return |
| 3447 |
} |
| 3448 |
|
| 3449 |
color := tui.ColInput |
| 3450 |
if t.paused { |
| 3451 |
color = tui.ColDisabled |
| 3452 |
} else if t.trackBlocked || t.waitFeedback() { |
| 3453 |
color = color.WithAttr(tui.Dim) |
| 3454 |
} |
| 3455 |
w.CPrint(color, string(before)) |
| 3456 |
w.CPrint(color, string(after)) |
| 3457 |
} |
| 3458 |
|
| 3459 |
func (t *Terminal) trimMessage(message string, maxWidth int) string { |
| 3460 |
if len(message) <= maxWidth { |
| 3461 |
return message |
| 3462 |
} |
| 3463 |
runes, _ := t.trimRight([]rune(message), maxWidth-2) |
| 3464 |
return string(runes) + strings.Repeat(".", util.Constrain(maxWidth, 0, 2)) |
| 3465 |
} |
| 3466 |
|
| 3467 |
func (t *Terminal) printInfo() { |
| 3468 |
if t.inputless { |
| 3469 |
return |
| 3470 |
} |
| 3471 |
t.withWindow(t.inputWindow, func() { t.printInfoImpl() }) |
| 3472 |
} |
| 3473 |
|
| 3474 |
func (t *Terminal) printInfoImpl() { |
| 3475 |
if t.window.Width() <= 1 || t.window.Height() == 0 { |
| 3476 |
return |
| 3477 |
} |
| 3478 |
pos := 0 |
| 3479 |
line := 0 |
| 3480 |
separatorLen := t.separatorLength() |
| 3481 |
maxHeight := t.window.Height() |
| 3482 |
move := func(y int, x int, clear bool) bool { |
| 3483 |
if y < 0 || y >= maxHeight { |
| 3484 |
return false |
| 3485 |
} |
| 3486 |
t.move(y, x, clear) |
| 3487 |
t.markOtherLine(y) |
| 3488 |
return true |
| 3489 |
} |
| 3490 |
printSpinner := func() { |
| 3491 |
if t.reading { |
| 3492 |
duration := int64(spinnerDuration) |
| 3493 |
idx := (time.Now().UnixNano() % (duration * int64(len(t.spinner)))) / duration |
| 3494 |
t.window.CPrint(tui.ColSpinner, t.spinner[idx]) |
| 3495 |
} else { |
| 3496 |
t.window.Print(" ") // Clear spinner |
| 3497 |
} |
| 3498 |
} |
| 3499 |
printInfoPrefix := func() { |
| 3500 |
str := t.infoPrefix |
| 3501 |
maxWidth := t.window.Width() - pos |
| 3502 |
width := util.StringWidth(str) |
| 3503 |
if width > maxWidth { |
| 3504 |
trimmed, _ := t.trimRight([]rune(str), maxWidth) |
| 3505 |
str = string(trimmed) |
| 3506 |
width = maxWidth |
| 3507 |
} |
| 3508 |
move(line, pos, separatorLen == 0) |
| 3509 |
if t.reading { |
| 3510 |
t.window.CPrint(tui.ColSpinner, str) |
| 3511 |
} else { |
| 3512 |
t.window.CPrint(tui.ColPrompt, str) |
| 3513 |
} |
| 3514 |
pos += width |
| 3515 |
} |
| 3516 |
printSeparator := func(fillLength int, pad bool) { |
| 3517 |
if separatorLen > 0 { |
| 3518 |
t.separator(t.window, fillLength) |
| 3519 |
t.window.Print(" ") |
| 3520 |
} else if pad { |
| 3521 |
t.window.Print(strings.Repeat(" ", fillLength+1)) |
| 3522 |
} |
| 3523 |
} |
| 3524 |
|
| 3525 |
if t.infoStyle == infoHidden { |
| 3526 |
if separatorLen > 0 { |
| 3527 |
if !move(line+1, 0, false) { |
| 3528 |
return |
| 3529 |
} |
| 3530 |
printSeparator(t.window.Width()-1, false) |
| 3531 |
} |
| 3532 |
return |
| 3533 |
} |
| 3534 |
|
| 3535 |
found := t.resultMerger.Length() |
| 3536 |
total := max(found, t.count) |
| 3537 |
output := fmt.Sprintf("%d/%d", found, total) |
| 3538 |
if t.multi > 0 { |
| 3539 |
if t.multi == maxMulti { |
| 3540 |
output += fmt.Sprintf(" (%d)", len(t.selected)) |
| 3541 |
} else { |
| 3542 |
output += fmt.Sprintf(" (%d/%d)", len(t.selected), t.multi) |
| 3543 |
} |
| 3544 |
} |
| 3545 |
if t.toggleSort { |
| 3546 |
if t.sort { |
| 3547 |
output += " +S" |
| 3548 |
} else { |
| 3549 |
output += " -S" |
| 3550 |
} |
| 3551 |
} |
| 3552 |
if t.track.Global() { |
| 3553 |
if t.trackBlocked { |
| 3554 |
output += " +T*" |
| 3555 |
} else { |
| 3556 |
output += " +T" |
| 3557 |
} |
| 3558 |
} else if t.track.Current() { |
| 3559 |
if t.trackBlocked { |
| 3560 |
output += " +t*" |
| 3561 |
} else { |
| 3562 |
output += " +t" |
| 3563 |
} |
| 3564 |
} |
| 3565 |
if t.waitFeedback() { |
| 3566 |
output += " (..)" |
| 3567 |
} |
| 3568 |
// Keep the search progress at the end so the other indicators don't shift |
| 3569 |
// as it appears and disappears. |
| 3570 |
if t.progress > 0 && t.progress < 100 { |
| 3571 |
output += fmt.Sprintf(" (%d%%)", t.progress) |
| 3572 |
} |
| 3573 |
if t.failed != nil && t.count == 0 { |
| 3574 |
output = fmt.Sprintf("[Command failed: %s]", *t.failed) |
| 3575 |
} |
| 3576 |
var outputPrinter labelPrinter |
| 3577 |
outputLen := len(output) |
| 3578 |
if t.infoCommand != "" { |
| 3579 |
output = t.executeCommand(t.infoCommand, false, true, true, true, output) |
| 3580 |
outputPrinter, outputLen = t.ansiLabelPrinter(output, &tui.ColInfo, false) |
| 3581 |
} |
| 3582 |
|
| 3583 |
shiftLen := t.queryLen[0] + t.queryLen[1] + 1 |
| 3584 |
if shiftLen == 1 && len(t.ghost) > 0 { |
| 3585 |
shiftLen = util.StringWidth(t.ghost) |
| 3586 |
} |
| 3587 |
switch t.infoStyle { |
| 3588 |
case infoDefault: |
| 3589 |
if !move(line+1, 0, separatorLen == 0) { |
| 3590 |
return |
| 3591 |
} |
| 3592 |
printSpinner() |
| 3593 |
t.window.Print(" ") // Margin |
| 3594 |
pos = 2 |
| 3595 |
case infoRight: |
| 3596 |
if !move(line+1, 0, false) { |
| 3597 |
return |
| 3598 |
} |
| 3599 |
case infoInlineRight: |
| 3600 |
pos = t.promptLen + shiftLen |
| 3601 |
case infoInline: |
| 3602 |
pos = t.promptLen + shiftLen |
| 3603 |
printInfoPrefix() |
| 3604 |
} |
| 3605 |
|
| 3606 |
if t.infoStyle == infoRight { |
| 3607 |
maxWidth := t.window.Width() - 1 |
| 3608 |
if t.reading { |
| 3609 |
// Need space for spinner and a margin column |
| 3610 |
maxWidth -= 2 |
| 3611 |
} |
| 3612 |
var fillLength int |
| 3613 |
if outputPrinter == nil { |
| 3614 |
output = t.trimMessage(output, maxWidth) |
| 3615 |
fillLength = t.window.Width() - len(output) - 2 |
| 3616 |
} else { |
| 3617 |
fillLength = t.window.Width() - outputLen - 2 |
| 3618 |
} |
| 3619 |
if t.reading { |
| 3620 |
if fillLength >= 2 { |
| 3621 |
printSeparator(fillLength-2, true) |
| 3622 |
} |
| 3623 |
printSpinner() |
| 3624 |
t.window.Print(" ") |
| 3625 |
} else if fillLength >= 0 { |
| 3626 |
printSeparator(fillLength, true) |
| 3627 |
} |
| 3628 |
if outputPrinter == nil { |
| 3629 |
t.window.CPrint(tui.ColInfo, output) |
| 3630 |
} else { |
| 3631 |
outputPrinter(t.window, maxWidth-1) |
| 3632 |
} |
| 3633 |
if fillLength >= 0 { |
| 3634 |
t.window.Print(" ") // Margin |
| 3635 |
} |
| 3636 |
return |
| 3637 |
} |
| 3638 |
|
| 3639 |
if t.infoStyle == infoInlineRight { |
| 3640 |
if len(t.infoPrefix) == 0 { |
| 3641 |
move(line, pos, false) |
| 3642 |
newPos := max(pos, t.window.Width()-outputLen-3) |
| 3643 |
t.window.Print(strings.Repeat(" ", newPos-pos)) |
| 3644 |
pos = newPos |
| 3645 |
if pos < t.window.Width() { |
| 3646 |
printSpinner() |
| 3647 |
pos++ |
| 3648 |
} |
| 3649 |
if pos < t.window.Width()-1 { |
| 3650 |
t.window.Print(" ") |
| 3651 |
pos++ |
| 3652 |
} |
| 3653 |
} else { |
| 3654 |
pos = max(pos, t.window.Width()-outputLen-util.StringWidth(t.infoPrefix)-1) |
| 3655 |
printInfoPrefix() |
| 3656 |
} |
| 3657 |
} |
| 3658 |
|
| 3659 |
maxWidth := t.window.Width() - pos - 1 |
| 3660 |
if outputPrinter == nil { |
| 3661 |
output = t.trimMessage(output, maxWidth) |
| 3662 |
t.window.CPrint(tui.ColInfo, output) |
| 3663 |
} else { |
| 3664 |
outputPrinter(t.window, maxWidth) |
| 3665 |
} |
| 3666 |
if t.infoStyle == infoInline && outputLen < maxWidth-1 && t.reading { |
| 3667 |
t.window.Print(" ") |
| 3668 |
printSpinner() |
| 3669 |
outputLen += 2 |
| 3670 |
} |
| 3671 |
|
| 3672 |
if t.infoStyle == infoInlineRight { |
| 3673 |
if separatorLen > 0 { |
| 3674 |
if !move(line+1, 0, false) { |
| 3675 |
return |
| 3676 |
} |
| 3677 |
printSeparator(t.window.Width()-1, false) |
| 3678 |
} |
| 3679 |
return |
| 3680 |
} |
| 3681 |
|
| 3682 |
fillLength := maxWidth - outputLen - 1 |
| 3683 |
if fillLength > 0 { |
| 3684 |
t.window.CPrint(tui.ColSeparator, " ") |
| 3685 |
printSeparator(fillLength, false) |
| 3686 |
} |
| 3687 |
} |
| 3688 |
|
| 3689 |
func (t *Terminal) resizeIfNeeded() bool { |
| 3690 |
// Check if input border is used and input has changed |
| 3691 |
if t.inputBorderShape.Visible() && t.inputWindow == nil && !t.inputless || t.inputWindow != nil && t.inputless { |
| 3692 |
t.printAll() |
| 3693 |
return true |
| 3694 |
} |
| 3695 |
|
| 3696 |
// Inline sections are budget-capped inside wborder, so window.Height() may be |
| 3697 |
// smaller than the requested content length. Treat "capped" (height < want) as |
| 3698 |
// a no-op to avoid triggering a full redraw on every info/header/footer event |
| 3699 |
// when the user has requested more content than fits. |
| 3700 |
mismatch := func(shape tui.BorderShape, height, want int) bool { |
| 3701 |
if shape == tui.BorderInline && height < want { |
| 3702 |
return false |
| 3703 |
} |
| 3704 |
return height != want |
| 3705 |
} |
| 3706 |
|
| 3707 |
// Check footer window |
| 3708 |
if len(t.footer) > 0 && (t.footerWindow == nil || mismatch(t.footerBorderShape, t.footerWindow.Height(), len(t.footer))) || |
| 3709 |
len(t.footer) == 0 && t.footerWindow != nil { |
| 3710 |
t.printAll() |
| 3711 |
return true |
| 3712 |
} |
| 3713 |
|
| 3714 |
// Check if the header borders are used and header has changed |
| 3715 |
allHeaderLines := t.visibleHeaderLines() |
| 3716 |
primaryHeaderLines := allHeaderLines |
| 3717 |
needHeaderWindow := t.hasHeaderWindow() |
| 3718 |
needHeaderLinesWindow := t.hasHeaderLinesWindow() |
| 3719 |
if needHeaderLinesWindow { |
| 3720 |
primaryHeaderLines -= t.headerLines |
| 3721 |
} |
| 3722 |
if (needHeaderWindow && t.headerWindow == nil) || |
| 3723 |
(!needHeaderWindow && t.headerWindow != nil) || |
| 3724 |
(needHeaderWindow && t.headerWindow != nil && mismatch(t.headerBorderShape, t.headerWindow.Height(), primaryHeaderLines)) || |
| 3725 |
(needHeaderLinesWindow && t.headerLinesWindow == nil) || |
| 3726 |
(!needHeaderLinesWindow && t.headerLinesWindow != nil) || |
| 3727 |
(needHeaderLinesWindow && t.headerLinesWindow != nil && mismatch(t.headerLinesShape, t.headerLinesWindow.Height(), t.headerLines)) { |
| 3728 |
t.printAll() |
| 3729 |
return true |
| 3730 |
} |
| 3731 |
return false |
| 3732 |
} |
| 3733 |
|
| 3734 |
func (t *Terminal) printHeader() { |
| 3735 |
if !t.headerVisible { |
| 3736 |
return |
| 3737 |
} |
| 3738 |
|
| 3739 |
// headerWindow is nil when hasHeaderWindow() returned false at resize time, |
| 3740 |
// e.g. --header-border=inline combined with empty header content. Don't |
| 3741 |
// delegate to printHeaderImpl because its nil-window branch folds the header |
| 3742 |
// into the list window, which isn't valid for inline. A nil window is only |
| 3743 |
// legitimate when the shape is NOT inline (e.g. header combined with the |
| 3744 |
// list when --no-list-border is in effect). |
| 3745 |
if !(t.headerBorderShape == tui.BorderInline && t.headerWindow == nil) { |
| 3746 |
t.withWindow(t.headerWindow, func() { |
| 3747 |
var headerItems []Item |
| 3748 |
if !t.hasHeaderLinesWindow() { |
| 3749 |
headerItems = t.header |
| 3750 |
} |
| 3751 |
t.printHeaderImpl(t.headerWindow, t.headerBorderShape, t.header0, headerItems) |
| 3752 |
}) |
| 3753 |
} |
| 3754 |
if w, shape := t.determineHeaderLinesShape(); w && |
| 3755 |
!(shape == tui.BorderInline && t.headerLinesWindow == nil) { |
| 3756 |
t.withWindow(t.headerLinesWindow, func() { |
| 3757 |
t.printHeaderImpl(t.headerLinesWindow, shape, nil, t.header) |
| 3758 |
}) |
| 3759 |
} |
| 3760 |
} |
| 3761 |
|
| 3762 |
func (t *Terminal) printFooter() { |
| 3763 |
if len(t.footer) == 0 { |
| 3764 |
return |
| 3765 |
} |
| 3766 |
indentSize := t.headerIndent(t.footerBorderShape) |
| 3767 |
indent := strings.Repeat(" ", indentSize) |
| 3768 |
max := min(len(t.footer), t.footerWindow.Height()) |
| 3769 |
|
| 3770 |
// Wrapping is not supported for footer |
| 3771 |
wrap := t.wrap |
| 3772 |
t.wrap = false |
| 3773 |
t.withWindow(t.footerWindow, func() { |
| 3774 |
var state *ansiState |
| 3775 |
for idx, lineStr := range t.footer[:max] { |
| 3776 |
line := idx |
| 3777 |
if t.layout != layoutReverse { |
| 3778 |
line = max - idx - 1 |
| 3779 |
} |
| 3780 |
trimmed, colors, newState := extractColor(lineStr, state, nil) |
| 3781 |
state = newState |
| 3782 |
item := &Item{ |
| 3783 |
text: util.ToChars([]byte(trimmed)), |
| 3784 |
colors: colors} |
| 3785 |
|
| 3786 |
t.printHighlighted(Result{item: item}, |
| 3787 |
tui.ColFooter, tui.ColFooter, false, false, false, line, line, true, |
| 3788 |
func(markerClass) int { |
| 3789 |
t.footerWindow.Print(indent) |
| 3790 |
return indentSize |
| 3791 |
}, nil, 0) |
| 3792 |
} |
| 3793 |
}) |
| 3794 |
t.wrap = wrap |
| 3795 |
} |
| 3796 |
|
| 3797 |
func (t *Terminal) headerIndent(borderShape tui.BorderShape) int { |
| 3798 |
return t.headerIndentImpl(t.pointerLen+t.markerLen, borderShape) |
| 3799 |
} |
| 3800 |
|
| 3801 |
func (t *Terminal) headerIndentImpl(base int, borderShape tui.BorderShape) int { |
| 3802 |
indentSize := base |
| 3803 |
if t.listBorderShape.HasLeft() { |
| 3804 |
indentSize += 1 + t.borderWidth |
| 3805 |
} |
| 3806 |
// Section borders with their own left side skip past the list border's left column. |
| 3807 |
// Inline sections also skip it, but only when the list border actually has a left, |
| 3808 |
// since otherwise the inline window starts flush with the list window. |
| 3809 |
if borderShape.HasLeft() || (borderShape == tui.BorderInline && t.listBorderShape.HasLeft()) { |
| 3810 |
indentSize -= 1 + t.borderWidth |
| 3811 |
if indentSize < 0 { |
| 3812 |
indentSize = 0 |
| 3813 |
} |
| 3814 |
} |
| 3815 |
return indentSize |
| 3816 |
} |
| 3817 |
|
| 3818 |
func (t *Terminal) printHeaderImpl(window tui.Window, borderShape tui.BorderShape, lines1 []string, lines2 []Item) { |
| 3819 |
max := t.window.Height() |
| 3820 |
var state *ansiState |
| 3821 |
needReverse := false |
| 3822 |
switch t.layout { |
| 3823 |
case layoutDefault, layoutReverseList: |
| 3824 |
needReverse = true |
| 3825 |
} |
| 3826 |
// Wrapping is not supported for header |
| 3827 |
wrap := t.wrap |
| 3828 |
|
| 3829 |
// Align header with the list |
| 3830 |
// fzf --header-lines 3 --style full --no-list-border |
| 3831 |
// fzf --header-lines 3 --style full --no-header-border |
| 3832 |
// fzf --header-lines 3 --style full --no-header-border --no-input-border |
| 3833 |
indentSize := t.pointerLen + t.markerLen |
| 3834 |
if window != nil { |
| 3835 |
indentSize = t.headerIndent(borderShape) |
| 3836 |
} |
| 3837 |
indent := strings.Repeat(" ", indentSize) |
| 3838 |
t.wrap = false |
| 3839 |
totalLines := len(lines1) + len(lines2) |
| 3840 |
for idx := 0; idx < totalLines; idx++ { |
| 3841 |
line := idx |
| 3842 |
if needReverse && idx < len(lines1) { |
| 3843 |
line = len(lines1) - idx - 1 |
| 3844 |
} |
| 3845 |
if !t.inputless && t.inputWindow == nil && window == nil && !t.headerFirst { |
| 3846 |
line++ |
| 3847 |
if !t.noSeparatorLine() { |
| 3848 |
line++ |
| 3849 |
} |
| 3850 |
} |
| 3851 |
if line >= max { |
| 3852 |
continue |
| 3853 |
} |
| 3854 |
|
| 3855 |
var item *Item |
| 3856 |
if idx < len(lines1) { |
| 3857 |
trimmed, colors, newState := extractColor(lines1[idx], state, nil) |
| 3858 |
state = newState |
| 3859 |
item = &Item{ |
| 3860 |
text: util.ToChars([]byte(trimmed)), |
| 3861 |
colors: colors} |
| 3862 |
} else { |
| 3863 |
headerItem := lines2[idx-len(lines1)] |
| 3864 |
item = &headerItem |
| 3865 |
} |
| 3866 |
|
| 3867 |
t.printHighlighted(Result{item: item}, |
| 3868 |
tui.ColHeader, tui.ColHeader, false, false, false, line, line, true, |
| 3869 |
func(markerClass) int { |
| 3870 |
t.window.Print(indent) |
| 3871 |
return indentSize |
| 3872 |
}, nil, 0) |
| 3873 |
} |
| 3874 |
t.wrap = wrap |
| 3875 |
} |
| 3876 |
|
| 3877 |
func (t *Terminal) canSpanMultiLines() bool { |
| 3878 |
return (t.multiLine || t.wrap || t.gap > 0) && t.inListWindow() |
| 3879 |
} |
| 3880 |
|
| 3881 |
func (t *Terminal) renderBar(line int, barRange [2]int) { |
| 3882 |
// If the screen is not filled with the list in non-multi-line mode, |
| 3883 |
// scrollbar is not visible at all. But in multi-line mode, we may need |
| 3884 |
// to redraw the scrollbar character at the end. |
| 3885 |
if t.canSpanMultiLines() { |
| 3886 |
t.prevLines[line].hasBar = t.printBar(line, true, barRange) |
| 3887 |
} |
| 3888 |
} |
| 3889 |
|
| 3890 |
func (t *Terminal) renderEmptyLine(line int, barRange [2]int) { |
| 3891 |
t.move(line, 0, true) |
| 3892 |
t.markEmptyLine(line) |
| 3893 |
t.renderBar(line, barRange) |
| 3894 |
} |
| 3895 |
|
| 3896 |
func (t *Terminal) gutter(current bool, alt bool) { |
| 3897 |
var color tui.ColorPair |
| 3898 |
if current { |
| 3899 |
color = tui.ColCurrentPointerEmpty |
| 3900 |
} else if !t.raw && t.gutterReverse || t.raw && t.gutterRawReverse { |
| 3901 |
if alt { |
| 3902 |
color = tui.ColAltPointerEmpty |
| 3903 |
} else { |
| 3904 |
color = tui.ColPointerEmpty |
| 3905 |
} |
| 3906 |
} else { |
| 3907 |
if alt { |
| 3908 |
color = tui.ColAltPointerEmptyChar |
| 3909 |
} else { |
| 3910 |
color = tui.ColPointerEmptyChar |
| 3911 |
} |
| 3912 |
} |
| 3913 |
gutter := t.pointerEmpty |
| 3914 |
if t.raw { |
| 3915 |
gutter = t.pointerEmptyRaw |
| 3916 |
} |
| 3917 |
t.window.CPrint(color, gutter) |
| 3918 |
} |
| 3919 |
|
| 3920 |
func (t *Terminal) renderGapLine(line int, barRange [2]int, drawLine bool) { |
| 3921 |
t.move(line, 0, false) |
| 3922 |
t.gutter(false, false) |
| 3923 |
t.window.Print(t.markerEmpty) |
| 3924 |
x := t.pointerLen + t.markerLen |
| 3925 |
|
| 3926 |
width := t.window.Width() - x - 1 |
| 3927 |
if drawLine && t.gapLine != nil { |
| 3928 |
t.gapLine(t.window, width) |
| 3929 |
} else { |
| 3930 |
t.move(line, x, true) |
| 3931 |
} |
| 3932 |
t.markOtherLine(line) |
| 3933 |
t.renderBar(line, barRange) |
| 3934 |
t.prevLines[line].width = width |
| 3935 |
} |
| 3936 |
|
| 3937 |
func (t *Terminal) printList() { |
| 3938 |
t.constrain() |
| 3939 |
barLength, barStart := t.getScrollbar() |
| 3940 |
|
| 3941 |
maxy := t.maxItems() - 1 |
| 3942 |
count := t.merger.Length() - t.offset |
| 3943 |
|
| 3944 |
// Start line |
| 3945 |
startLine := t.promptLines() + t.visibleHeaderLinesInList() |
| 3946 |
maxy += startLine |
| 3947 |
|
| 3948 |
barRange := [2]int{startLine + barStart, startLine + barStart + barLength} |
| 3949 |
for line, itemCount := startLine, 0; line <= maxy; line, itemCount = line+1, itemCount+1 { |
| 3950 |
if itemCount < count { |
| 3951 |
item := t.merger.Get(itemCount + t.offset) |
| 3952 |
current := itemCount == t.cy-t.offset |
| 3953 |
line = t.printItem(item, line, maxy, itemCount, current, barRange) |
| 3954 |
} else if !t.prevLines[line].empty { |
| 3955 |
t.renderEmptyLine(line, barRange) |
| 3956 |
} |
| 3957 |
} |
| 3958 |
} |
| 3959 |
|
| 3960 |
func (t *Terminal) printBar(lineNum int, forceRedraw bool, barRange [2]int) bool { |
| 3961 |
hasBar := lineNum >= barRange[0] && lineNum < barRange[1] |
| 3962 |
if (hasBar != t.prevLines[lineNum].hasBar || forceRedraw) && t.window.Width() > 0 { |
| 3963 |
if len(t.scrollbar) > 0 { |
| 3964 |
t.move(lineNum, t.window.Width()-1, true) |
| 3965 |
if hasBar { |
| 3966 |
t.window.CPrint(tui.ColScrollbar, t.scrollbar) |
| 3967 |
} |
| 3968 |
} |
| 3969 |
} |
| 3970 |
return hasBar |
| 3971 |
} |
| 3972 |
|
| 3973 |
func (t *Terminal) printItem(result Result, line int, maxLine int, index int, current bool, barRange [2]int) int { |
| 3974 |
item := result.item |
| 3975 |
matched := true |
| 3976 |
var matchResult Result |
| 3977 |
if t.raw { |
| 3978 |
if matchResult, matched = t.matchMap[item.Index()]; matched { |
| 3979 |
result = matchResult |
| 3980 |
} |
| 3981 |
} |
| 3982 |
|
| 3983 |
_, selected := t.selected[item.Index()] |
| 3984 |
label := "" |
| 3985 |
extraWidth := 0 |
| 3986 |
alt := false |
| 3987 |
altBg := t.theme.AltBg |
| 3988 |
selectedBg := selected && t.theme.SelectedBg != t.theme.ListBg |
| 3989 |
if t.jumping != jumpDisabled { |
| 3990 |
if index < len(t.jumpLabels) { |
| 3991 |
// Striped |
| 3992 |
if !altBg.IsColorDefined() { |
| 3993 |
altBg = t.theme.DarkBg |
| 3994 |
alt = index%2 == 0 |
| 3995 |
} else { |
| 3996 |
alt = index%2 == 1 |
| 3997 |
} |
| 3998 |
label = t.jumpLabels[index:index+1] + strings.Repeat(" ", max(0, t.pointerLen-1)) |
| 3999 |
if t.pointerLen == 0 { |
| 4000 |
extraWidth = 1 |
| 4001 |
} |
| 4002 |
} |
| 4003 |
} else { |
| 4004 |
if current { |
| 4005 |
label = t.pointer |
| 4006 |
} |
| 4007 |
alt = !selectedBg && altBg.IsColorDefined() && index%2 == 1 |
| 4008 |
} |
| 4009 |
|
| 4010 |
// Avoid unnecessary redraw |
| 4011 |
numLines, _ := t.numItemLines(item, maxLine-line+1) |
| 4012 |
newLine := itemLine{valid: true, firstLine: line, numLines: numLines, cy: index + t.offset, current: current, selected: selected, label: label, |
| 4013 |
result: result, queryLen: len(t.input), width: 0, hasBar: line >= barRange[0] && line < barRange[1], hidden: !matched} |
| 4014 |
prevLine := t.prevLines[line] |
| 4015 |
forceRedraw := !prevLine.valid || prevLine.other || prevLine.firstLine != newLine.firstLine |
| 4016 |
printBar := func(lineNum int, forceRedraw bool) bool { |
| 4017 |
return t.printBar(lineNum, forceRedraw, barRange) |
| 4018 |
} |
| 4019 |
|
| 4020 |
if !forceRedraw && |
| 4021 |
prevLine.hidden == newLine.hidden && |
| 4022 |
prevLine.numLines == newLine.numLines && |
| 4023 |
prevLine.current == newLine.current && |
| 4024 |
prevLine.selected == newLine.selected && |
| 4025 |
prevLine.label == newLine.label && |
| 4026 |
prevLine.queryLen == newLine.queryLen && |
| 4027 |
prevLine.result == newLine.result { |
| 4028 |
t.prevLines[line].hasBar = printBar(line, false) |
| 4029 |
return line + numLines - 1 |
| 4030 |
} |
| 4031 |
|
| 4032 |
maxWidth := t.window.Width() - (t.pointerLen + t.markerLen + t.barCol()) |
| 4033 |
postTask := func(lineNum int, width int, wrapped bool, forceRedraw bool, lbg tui.ColorPair) { |
| 4034 |
width += extraWidth |
| 4035 |
if (current || selected || alt) && t.highlightLine || lbg.IsFullBgMarker() { |
| 4036 |
color := tui.ColSelected |
| 4037 |
if lbg.IsFullBgMarker() { |
| 4038 |
color = lbg |
| 4039 |
} else if current { |
| 4040 |
color = tui.ColCurrent |
| 4041 |
} else if alt { |
| 4042 |
color = color.WithBg(altBg) |
| 4043 |
} |
| 4044 |
fillSpaces := maxWidth - width |
| 4045 |
if wrapped { |
| 4046 |
fillSpaces -= t.wrapSignWidth |
| 4047 |
} |
| 4048 |
if fillSpaces > 0 { |
| 4049 |
t.window.CPrint(color, strings.Repeat(" ", fillSpaces)) |
| 4050 |
} |
| 4051 |
newLine.width = maxWidth |
| 4052 |
} else { |
| 4053 |
var fillSpaces int |
| 4054 |
if forceRedraw { |
| 4055 |
fillSpaces = maxWidth - width |
| 4056 |
} else { |
| 4057 |
fillSpaces = t.prevLines[lineNum].width - width |
| 4058 |
} |
| 4059 |
if wrapped { |
| 4060 |
fillSpaces -= t.wrapSignWidth |
| 4061 |
} |
| 4062 |
if fillSpaces > 0 { |
| 4063 |
t.window.Print(strings.Repeat(" ", fillSpaces)) |
| 4064 |
} |
| 4065 |
newLine.width = width |
| 4066 |
if wrapped { |
| 4067 |
newLine.width += t.wrapSignWidth |
| 4068 |
} |
| 4069 |
} |
| 4070 |
// When width is 0, line is completely cleared. We need to redraw scrollbar |
| 4071 |
newLine.hasBar = printBar(lineNum, forceRedraw || width == 0) |
| 4072 |
t.prevLines[lineNum] = newLine |
| 4073 |
} |
| 4074 |
|
| 4075 |
var finalLineNum int |
| 4076 |
markerFor := func(markerClass markerClass) string { |
| 4077 |
marker := t.marker |
| 4078 |
switch markerClass { |
| 4079 |
case markerTop: |
| 4080 |
marker = t.markerMultiLine[0] |
| 4081 |
case markerMiddle: |
| 4082 |
marker = t.markerMultiLine[1] |
| 4083 |
case markerBottom: |
| 4084 |
marker = t.markerMultiLine[2] |
| 4085 |
} |
| 4086 |
return marker |
| 4087 |
} |
| 4088 |
indentSize := t.pointerLen + t.markerLen |
| 4089 |
if current { |
| 4090 |
preTask := func(marker markerClass) int { |
| 4091 |
w := t.window.Width() - t.pointerLen |
| 4092 |
if w < 0 { |
| 4093 |
return indentSize |
| 4094 |
} |
| 4095 |
if len(label) == 0 { |
| 4096 |
t.gutter(true, false) |
| 4097 |
} else { |
| 4098 |
t.window.CPrint(tui.ColCurrentPointer, label) |
| 4099 |
} |
| 4100 |
if w-t.markerLen < 0 { |
| 4101 |
return indentSize |
| 4102 |
} |
| 4103 |
if selected { |
| 4104 |
t.window.CPrint(tui.ColCurrentMarker, markerFor(marker)) |
| 4105 |
} else { |
| 4106 |
t.window.CPrint(tui.ColCurrentSelectedEmpty, t.markerEmpty) |
| 4107 |
} |
| 4108 |
return indentSize |
| 4109 |
} |
| 4110 |
colCurrent := tui.ColCurrent |
| 4111 |
nthOverlay := t.theme.NthCurrentAttr |
| 4112 |
if selected { |
| 4113 |
nthOverlay = t.theme.NthSelectedAttr.Merge(t.theme.NthCurrentAttr) |
| 4114 |
baseAttr := tui.ColNormal.Attr().Merge(t.theme.NthSelectedAttr).Merge(t.theme.NthCurrentAttr) |
| 4115 |
colCurrent = colCurrent.WithNewAttr(baseAttr) |
| 4116 |
} |
| 4117 |
finalLineNum = t.printHighlighted(result, colCurrent, tui.ColCurrentMatch, true, true, !matched, line, maxLine, forceRedraw, preTask, postTask, nthOverlay) |
| 4118 |
} else { |
| 4119 |
preTask := func(marker markerClass) int { |
| 4120 |
w := t.window.Width() - t.pointerLen |
| 4121 |
if w < 0 { |
| 4122 |
return indentSize |
| 4123 |
} |
| 4124 |
if len(label) == 0 { |
| 4125 |
t.gutter(false, index%2 == 1) |
| 4126 |
} else { |
| 4127 |
t.window.CPrint(tui.ColPointer, label) |
| 4128 |
} |
| 4129 |
if w-t.markerLen < 0 { |
| 4130 |
return indentSize |
| 4131 |
} |
| 4132 |
if selected { |
| 4133 |
t.window.CPrint(tui.ColMarker, markerFor(marker)) |
| 4134 |
} else { |
| 4135 |
t.window.Print(t.markerEmpty) |
| 4136 |
} |
| 4137 |
return indentSize |
| 4138 |
} |
| 4139 |
var base, match tui.ColorPair |
| 4140 |
if selected { |
| 4141 |
base = tui.ColSelected |
| 4142 |
match = tui.ColSelectedMatch |
| 4143 |
} else { |
| 4144 |
base = tui.ColNormal |
| 4145 |
match = tui.ColMatch |
| 4146 |
} |
| 4147 |
if alt { |
| 4148 |
base = base.WithBg(altBg) |
| 4149 |
match = match.WithBg(altBg) |
| 4150 |
} |
| 4151 |
var nthOverlay tui.Attr |
| 4152 |
if selected { |
| 4153 |
nthOverlay = t.theme.NthSelectedAttr |
| 4154 |
} |
| 4155 |
finalLineNum = t.printHighlighted(result, base, match, false, true, !matched, line, maxLine, forceRedraw, preTask, postTask, nthOverlay) |
| 4156 |
} |
| 4157 |
for i := 0; i < t.gap && finalLineNum < maxLine; i++ { |
| 4158 |
finalLineNum++ |
| 4159 |
t.renderGapLine(finalLineNum, barRange, i == t.gap-1) |
| 4160 |
} |
| 4161 |
return finalLineNum |
| 4162 |
} |
| 4163 |
|
| 4164 |
func (t *Terminal) trimRight(runes []rune, width int) ([]rune, bool) { |
| 4165 |
// We start from the beginning to handle tab characters |
| 4166 |
_, overflowIdx := util.RunesWidth(runes, 0, t.tabstop, width) |
| 4167 |
if overflowIdx >= 0 { |
| 4168 |
return runes[:overflowIdx], true |
| 4169 |
} |
| 4170 |
return runes, false |
| 4171 |
} |
| 4172 |
|
| 4173 |
func (t *Terminal) displayWidthWithLimit(runes []rune, prefixWidth int, limit int) int { |
| 4174 |
width, _ := util.RunesWidth(runes, prefixWidth, t.tabstop, limit) |
| 4175 |
return width |
| 4176 |
} |
| 4177 |
|
| 4178 |
func (t *Terminal) trimLeft(runes []rune, width int, ellipsisWidth int) ([]rune, int32) { |
| 4179 |
width = max(0, width) |
| 4180 |
var trimmed int32 |
| 4181 |
|
| 4182 |
str := string(runes) |
| 4183 |
runningSum := 0 |
| 4184 |
runningSumAdjusted := 0 |
| 4185 |
// We can't just subtract the width on each segment because there might be |
| 4186 |
// a tab character afterwards. For example, with the tabstop = 8: |
| 4187 |
// 1234____5678 |
| 4188 |
// 234_____5678 |
| 4189 |
// 34______5678 |
| 4190 |
// 4_______5678 |
| 4191 |
// ________5678 |
| 4192 |
// 5678 |
| 4193 |
// 678 |
| 4194 |
// 78 |
| 4195 |
// 8 |
| 4196 |
// We need to look ahead, but not to the end to avoid performance hit. |
| 4197 |
type queuedSegment struct { |
| 4198 |
rs []rune |
| 4199 |
w int |
| 4200 |
} |
| 4201 |
allQueue := []queuedSegment{} |
| 4202 |
queuedWidth := 0 |
| 4203 |
limit := width - ellipsisWidth |
| 4204 |
processQueue := func() { |
| 4205 |
for idx, item := range allQueue { |
| 4206 |
if runningSumAdjusted <= limit { |
| 4207 |
allQueue = allQueue[idx:] |
| 4208 |
return |
| 4209 |
} |
| 4210 |
runningSumAdjusted -= item.w |
| 4211 |
runes = runes[len(item.rs):] |
| 4212 |
trimmed += int32(len(item.rs)) |
| 4213 |
} |
| 4214 |
allQueue = []queuedSegment{} |
| 4215 |
} |
| 4216 |
|
| 4217 |
gr := uniseg.NewGraphemes(str) |
| 4218 |
queue := []queuedSegment{} |
| 4219 |
for gr.Next() { |
| 4220 |
s := gr.Str() |
| 4221 |
rs := gr.Runes() |
| 4222 |
|
| 4223 |
var w int |
| 4224 |
if len(rs) == 1 && rs[0] == '\t' { |
| 4225 |
w = t.tabstop - runningSum%t.tabstop |
| 4226 |
} else { |
| 4227 |
w = util.StringWidth(string(rs)) |
| 4228 |
} |
| 4229 |
runningSum += w |
| 4230 |
runningSumAdjusted += w |
| 4231 |
queue = append(queue, queuedSegment{rs: rs, w: w}) |
| 4232 |
queuedWidth += w |
| 4233 |
if queuedWidth >= t.tabstop || s == "\t" { |
| 4234 |
queuedWidth = 0 |
| 4235 |
|
| 4236 |
if s == "\t" { |
| 4237 |
queue[len(queue)-1].w = t.tabstop |
| 4238 |
for idx := range queue[:len(queue)-1] { |
| 4239 |
queue[idx].w = 0 |
| 4240 |
} |
| 4241 |
} |
| 4242 |
allQueue = append(allQueue, queue...) |
| 4243 |
queue = []queuedSegment{} |
| 4244 |
processQueue() |
| 4245 |
} |
| 4246 |
} |
| 4247 |
allQueue = append(allQueue, queue...) |
| 4248 |
processQueue() |
| 4249 |
return runes, trimmed |
| 4250 |
} |
| 4251 |
|
| 4252 |
func (t *Terminal) overflow(runes []rune, max int) bool { |
| 4253 |
return t.displayWidthWithLimit(runes, 0, max) > max |
| 4254 |
} |
| 4255 |
|
| 4256 |
func (t *Terminal) printHighlighted(result Result, colBase tui.ColorPair, colMatch tui.ColorPair, current bool, match bool, hidden bool, lineNum int, maxLineNum int, forceRedraw bool, preTask func(markerClass) int, postTask func(int, int, bool, bool, tui.ColorPair), nthOverlay tui.Attr) int { |
| 4257 |
var displayWidth int |
| 4258 |
item := result.item |
| 4259 |
matchOffsets := []Offset{} |
| 4260 |
var pos *[]int |
| 4261 |
if match && t.resultMerger.pattern != nil { |
| 4262 |
_, matchOffsets, pos = t.resultMerger.pattern.MatchItem(item, true, t.slab) |
| 4263 |
} |
| 4264 |
charOffsets := matchOffsets |
| 4265 |
if pos != nil { |
| 4266 |
runes := item.text.ToRunes() |
| 4267 |
charOffsets = make([]Offset, len(*pos)) |
| 4268 |
for idx, p := range *pos { |
| 4269 |
gr := uniseg.NewGraphemes(string(runes[p:])) |
| 4270 |
w := 1 |
| 4271 |
for gr.Next() { |
| 4272 |
w = len(gr.Runes()) |
| 4273 |
break |
| 4274 |
} |
| 4275 |
offset := Offset{int32(p), int32(p + w)} |
| 4276 |
charOffsets[idx] = offset |
| 4277 |
} |
| 4278 |
slices.SortFunc(charOffsets, compareOffsets) |
| 4279 |
} |
| 4280 |
|
| 4281 |
// When postTask is nil, we're printing header lines. No need to care about nth. |
| 4282 |
var nthOffsets []Offset |
| 4283 |
if postTask != nil { |
| 4284 |
wholeCovered := len(t.nthCurrent) == 0 |
| 4285 |
for _, nth := range t.nthCurrent { |
| 4286 |
// Do we still want to apply a different style when the current nth |
| 4287 |
// covers the whole string? Probably not. And we can simplify the logic. |
| 4288 |
if nth.IsFull() { |
| 4289 |
wholeCovered = true |
| 4290 |
break |
| 4291 |
} |
| 4292 |
} |
| 4293 |
if wholeCovered && t.nthAttr&tui.AttrRegular > 0 { |
| 4294 |
// But if 'nth' is set to 'regular', it's a sign that you're applying |
| 4295 |
// a different style to the rest of the string. e.g. 'nth:regular,fg:dim' |
| 4296 |
// In this case, we still need to apply it to clear the style. |
| 4297 |
fgAttr := tui.ColNormal.Attr() |
| 4298 |
nthAttrFinal := fgAttr.Merge(t.nthAttr).Merge(nthOverlay) |
| 4299 |
colBase = colBase.WithNewAttr(nthAttrFinal) |
| 4300 |
} |
| 4301 |
if !wholeCovered && t.nthAttr > 0 { |
| 4302 |
var tokens []Token |
| 4303 |
if item.transformed != nil && item.transformed.revision == t.resultMerger.revision { |
| 4304 |
tokens = item.transformed.tokens |
| 4305 |
} else { |
| 4306 |
tokens = Transform(Tokenize(item.text.ToString(), t.delimiter), t.nthCurrent) |
| 4307 |
} |
| 4308 |
nthOffsets = make([]Offset, len(tokens)) |
| 4309 |
for i, token := range tokens { |
| 4310 |
start := token.prefixLength |
| 4311 |
length := token.text.Length() - token.text.TrailingWhitespaces() |
| 4312 |
end := start + int32(length) |
| 4313 |
nthOffsets[i] = Offset{int32(start), int32(end)} |
| 4314 |
} |
| 4315 |
slices.SortFunc(nthOffsets, compareOffsets) |
| 4316 |
} |
| 4317 |
} |
| 4318 |
allOffsets := result.colorOffsets(charOffsets, nthOffsets, t.theme, colBase, colMatch, t.nthAttr, nthOverlay, hidden) |
| 4319 |
|
| 4320 |
// Determine split offset for horizontal scrolling with freeze |
| 4321 |
splitOffset1 := -1 |
| 4322 |
splitOffset2 := -1 |
| 4323 |
if t.hscroll && !t.wrap { |
| 4324 |
var tokens []Token |
| 4325 |
if t.freezeLeft > 0 || t.freezeRight > 0 { |
| 4326 |
tokens = Tokenize(item.text.ToString(), t.delimiter) |
| 4327 |
} |
| 4328 |
|
| 4329 |
// 0 | 1 | 2 | 3 | 4 | 5 |
| 4330 |
// ------> <------ |
| 4331 |
if t.freezeLeft > 0 { |
| 4332 |
if len(tokens) > 0 { |
| 4333 |
token := tokens[min(t.freezeLeft, len(tokens))-1] |
| 4334 |
splitOffset1 = int(token.prefixLength) + token.text.Length() - token.text.TrailingWhitespaces() |
| 4335 |
} |
| 4336 |
} |
| 4337 |
if t.freezeRight > 0 { |
| 4338 |
index := max(t.freezeLeft-1, len(tokens)-t.freezeRight-1) |
| 4339 |
if index < 0 { |
| 4340 |
splitOffset2 = 0 |
| 4341 |
} else if index >= t.freezeLeft { |
| 4342 |
token := tokens[index] |
| 4343 |
delimiter := strings.TrimLeftFunc(GetLastDelimiter(token.text.ToString(), t.delimiter), unicode.IsSpace) |
| 4344 |
splitOffset2 = int(token.prefixLength) + token.text.Length() - len([]rune(delimiter)) |
| 4345 |
} |
| 4346 |
splitOffset2 = max(splitOffset2, splitOffset1) |
| 4347 |
} |
| 4348 |
} |
| 4349 |
|
| 4350 |
maxLines := 1 |
| 4351 |
if t.canSpanMultiLines() { |
| 4352 |
maxLines = maxLineNum - lineNum + 1 |
| 4353 |
} |
| 4354 |
lines, overflow := t.itemLines(item, maxLines) |
| 4355 |
numItemLines := len(lines) |
| 4356 |
|
| 4357 |
finalLineNum := lineNum |
| 4358 |
topCutoff := false |
| 4359 |
skipLines := 0 |
| 4360 |
wrapped := false |
| 4361 |
if t.canSpanMultiLines() { |
| 4362 |
// Cut off the upper lines in the 'default' layout |
| 4363 |
if t.layout == layoutDefault && !current && maxLines == numItemLines && overflow { |
| 4364 |
lines, _ = t.itemLines(item, math.MaxInt) |
| 4365 |
|
| 4366 |
// To see if the first visible line is wrapped, we need to check the last cut-off line |
| 4367 |
prevLine := lines[len(lines)-maxLines-1] |
| 4368 |
if len(prevLine) == 0 || prevLine[len(prevLine)-1] != '\n' { |
| 4369 |
wrapped = true |
| 4370 |
} |
| 4371 |
|
| 4372 |
skipLines = len(lines) - maxLines |
| 4373 |
topCutoff = true |
| 4374 |
} |
| 4375 |
} |
| 4376 |
from := 0 |
| 4377 |
for lineOffset := 0; lineOffset < len(lines) && (lineNum <= maxLineNum || maxLineNum == 0); lineOffset++ { |
| 4378 |
line := lines[lineOffset] |
| 4379 |
finalLineNum = lineNum |
| 4380 |
offsets := []colorOffset{} |
| 4381 |
lbg := tui.NoColorPair() |
| 4382 |
for idx, offset := range allOffsets { |
| 4383 |
lineEnd := int32(from + len(line)) |
| 4384 |
if offset.offset[0] >= lineEnd { |
| 4385 |
if offset.IsFullBgMarker(lineEnd) { |
| 4386 |
lbg = offset.color |
| 4387 |
} |
| 4388 |
allOffsets = allOffsets[idx:] |
| 4389 |
break |
| 4390 |
} |
| 4391 |
|
| 4392 |
if offset.offset[0] < int32(from) { |
| 4393 |
continue |
| 4394 |
} |
| 4395 |
|
| 4396 |
if offset.offset[1] < lineEnd { |
| 4397 |
offset.offset[0] -= int32(from) |
| 4398 |
offset.offset[1] -= int32(from) |
| 4399 |
offsets = append(offsets, offset) |
| 4400 |
} else { |
| 4401 |
if idx < len(allOffsets)-1 { |
| 4402 |
next := allOffsets[idx+1] |
| 4403 |
if next.IsFullBgMarker(lineEnd) { |
| 4404 |
lbg = next.color |
| 4405 |
idx++ |
| 4406 |
} |
| 4407 |
} |
| 4408 |
dupe := offset |
| 4409 |
dupe.offset[0] = lineEnd |
| 4410 |
|
| 4411 |
offset.offset[0] -= int32(from) |
| 4412 |
offset.offset[1] = lineEnd |
| 4413 |
offsets = append(offsets, offset) |
| 4414 |
|
| 4415 |
allOffsets = append([]colorOffset{dupe}, allOffsets[idx+1:]...) |
| 4416 |
break |
| 4417 |
} |
| 4418 |
} |
| 4419 |
splitOffsetLeft := 0 |
| 4420 |
if splitOffset1 >= 0 && splitOffset1 > from && splitOffset1 < from+len(line) { |
| 4421 |
splitOffsetLeft = splitOffset1 - from |
| 4422 |
} |
| 4423 |
splitOffsetRight := -1 |
| 4424 |
if splitOffset2 >= 0 && splitOffset2 >= from && splitOffset2 < from+len(line) { |
| 4425 |
splitOffsetRight = splitOffset2 - from |
| 4426 |
} |
| 4427 |
from += len(line) |
| 4428 |
if lineOffset < skipLines { |
| 4429 |
continue |
| 4430 |
} |
| 4431 |
actualLineOffset := lineOffset - skipLines |
| 4432 |
|
| 4433 |
var maxEnd int |
| 4434 |
for _, offset := range offsets { |
| 4435 |
if offset.match { |
| 4436 |
maxEnd = max(maxEnd, int(offset.offset[1])) |
| 4437 |
} |
| 4438 |
} |
| 4439 |
|
| 4440 |
actualLineNum := lineNum |
| 4441 |
if t.layout == layoutDefault { |
| 4442 |
actualLineNum = (lineNum - actualLineOffset) + (numItemLines - actualLineOffset) - 1 |
| 4443 |
} |
| 4444 |
t.move(actualLineNum, 0, forceRedraw && postTask == nil) |
| 4445 |
|
| 4446 |
indentSize := t.pointerLen + t.markerLen |
| 4447 |
if preTask != nil { |
| 4448 |
var marker markerClass |
| 4449 |
if numItemLines == 1 { |
| 4450 |
if !overflow { |
| 4451 |
marker = markerSingle |
| 4452 |
} else if topCutoff { |
| 4453 |
marker = markerBottom |
| 4454 |
} else { |
| 4455 |
marker = markerTop |
| 4456 |
} |
| 4457 |
} else { |
| 4458 |
if actualLineOffset == 0 { // First line |
| 4459 |
if topCutoff { |
| 4460 |
marker = markerMiddle |
| 4461 |
} else { |
| 4462 |
marker = markerTop |
| 4463 |
} |
| 4464 |
} else if actualLineOffset == numItemLines-1 { // Last line |
| 4465 |
if topCutoff || !overflow { |
| 4466 |
marker = markerBottom |
| 4467 |
} else { |
| 4468 |
marker = markerMiddle |
| 4469 |
} |
| 4470 |
} else { |
| 4471 |
marker = markerMiddle |
| 4472 |
} |
| 4473 |
} |
| 4474 |
|
| 4475 |
indentSize = preTask(marker) |
| 4476 |
} |
| 4477 |
|
| 4478 |
maxWidth := t.window.Width() - (indentSize + t.barCol()) |
| 4479 |
wasWrapped := false |
| 4480 |
if wrapped { |
| 4481 |
wrapSign := t.wrapSign |
| 4482 |
if maxWidth < t.wrapSignWidth { |
| 4483 |
runes, _ := util.Truncate(wrapSign, maxWidth) |
| 4484 |
wrapSign = string(runes) |
| 4485 |
maxWidth = 0 |
| 4486 |
} else { |
| 4487 |
maxWidth -= t.wrapSignWidth |
| 4488 |
} |
| 4489 |
t.window.CPrint(colBase.WithAttr(tui.Dim), wrapSign) |
| 4490 |
wrapped = false |
| 4491 |
wasWrapped = true |
| 4492 |
} |
| 4493 |
|
| 4494 |
if len(line) > 0 && line[len(line)-1] == '\n' && lineOffset < len(lines)-1 { |
| 4495 |
line = line[:len(line)-1] |
| 4496 |
} else { |
| 4497 |
wrapped = true |
| 4498 |
} |
| 4499 |
|
| 4500 |
frozenLeft := line[:splitOffsetLeft] |
| 4501 |
middle := line[splitOffsetLeft:] |
| 4502 |
frozenRight := []rune{} |
| 4503 |
if splitOffsetRight >= splitOffsetLeft { |
| 4504 |
middle = line[splitOffsetLeft:splitOffsetRight] |
| 4505 |
frozenRight = line[splitOffsetRight:] |
| 4506 |
} |
| 4507 |
displayWidthSum := 0 |
| 4508 |
displayWidthLeft := 0 |
| 4509 |
todo := [3]func(){} |
| 4510 |
for fidx, runes := range [][]rune{frozenLeft, frozenRight, middle} { |
| 4511 |
if len(runes) == 0 { |
| 4512 |
continue |
| 4513 |
} |
| 4514 |
shift := 0 |
| 4515 |
maxe := maxEnd |
| 4516 |
offs := make([]colorOffset, len(offsets)) |
| 4517 |
for idx := range offsets { |
| 4518 |
offs[idx] = offsets[idx] |
| 4519 |
if fidx == 1 && splitOffsetRight > 0 { |
| 4520 |
shift = splitOffsetRight |
| 4521 |
} else if fidx == 2 && splitOffsetLeft > 0 { |
| 4522 |
shift = splitOffsetLeft |
| 4523 |
} |
| 4524 |
offs[idx].offset[0] -= int32(shift) |
| 4525 |
offs[idx].offset[1] -= int32(shift) |
| 4526 |
} |
| 4527 |
maxe -= shift |
| 4528 |
ellipsis, ellipsisWidth := util.Truncate(t.ellipsis, maxWidth) |
| 4529 |
adjustedMaxWidth := maxWidth |
| 4530 |
if fidx < 2 { |
| 4531 |
// For frozen parts, reserve space for the ellipsis in the middle part |
| 4532 |
adjustedMaxWidth -= ellipsisWidth |
| 4533 |
} |
| 4534 |
var prefixWidth int |
| 4535 |
if fidx == 2 { |
| 4536 |
prefixWidth = displayWidthLeft |
| 4537 |
} |
| 4538 |
displayWidth = t.displayWidthWithLimit(runes, prefixWidth, adjustedMaxWidth) |
| 4539 |
if !t.wrap && displayWidth > adjustedMaxWidth { |
| 4540 |
maxe = util.Constrain(maxe+min(maxWidth/2-ellipsisWidth, t.hscrollOff), 0, len(runes)) |
| 4541 |
transformOffsets := func(diff int32) { |
| 4542 |
for idx := range offs { |
| 4543 |
offs[idx].offset[0] -= diff |
| 4544 |
offs[idx].offset[1] -= diff |
| 4545 |
} |
| 4546 |
} |
| 4547 |
if t.hscroll { |
| 4548 |
if fidx == 1 || fidx == 2 && t.keepRight && pos == nil { |
| 4549 |
trimmed, diff := t.trimLeft(runes, maxWidth, ellipsisWidth) |
| 4550 |
transformOffsets(diff - int32(len(ellipsis))) |
| 4551 |
runes = append(ellipsis, trimmed...) |
| 4552 |
} else if fidx == 0 || !t.overflow(runes[:maxe], maxWidth-ellipsisWidth) { |
| 4553 |
// Stri.. |
| 4554 |
runes, _ = t.trimRight(runes, maxWidth-ellipsisWidth) |
| 4555 |
runes = append(runes, ellipsis...) |
| 4556 |
} else { |
| 4557 |
// Stri.. |
| 4558 |
if t.overflow(runes[maxe:], ellipsisWidth) { |
| 4559 |
runes = append(runes[:maxe], ellipsis...) |
| 4560 |
} |
| 4561 |
// ..ri.. |
| 4562 |
var diff int32 |
| 4563 |
runes, diff = t.trimLeft(runes, maxWidth, ellipsisWidth) |
| 4564 |
|
| 4565 |
// Transform offsets |
| 4566 |
transformOffsets(diff - int32(len(ellipsis))) |
| 4567 |
runes = append(ellipsis, runes...) |
| 4568 |
} |
| 4569 |
} else { |
| 4570 |
runes, _ = t.trimRight(runes, maxWidth-ellipsisWidth) |
| 4571 |
runes = append(runes, ellipsis...) |
| 4572 |
} |
| 4573 |
displayWidth = t.displayWidthWithLimit(runes, 0, maxWidth) |
| 4574 |
} |
| 4575 |
displayWidthSum += displayWidth |
| 4576 |
if fidx == 0 { |
| 4577 |
displayWidthLeft = displayWidth |
| 4578 |
} |
| 4579 |
|
| 4580 |
if maxWidth > 0 { |
| 4581 |
color := colBase |
| 4582 |
if hidden { |
| 4583 |
color = color.WithFg(t.theme.Nomatch) |
| 4584 |
} |
| 4585 |
todo[fidx] = func() { |
| 4586 |
t.printColoredString(t.window, runes, offs, color, prefixWidth) |
| 4587 |
} |
| 4588 |
} else { |
| 4589 |
break |
| 4590 |
} |
| 4591 |
maxWidth -= displayWidth |
| 4592 |
} |
| 4593 |
if todo[0] != nil { |
| 4594 |
todo[0]() |
| 4595 |
} |
| 4596 |
if todo[2] != nil { |
| 4597 |
todo[2]() |
| 4598 |
} |
| 4599 |
if todo[1] != nil { |
| 4600 |
todo[1]() |
| 4601 |
} |
| 4602 |
if postTask != nil { |
| 4603 |
postTask(actualLineNum, displayWidthSum, wasWrapped, forceRedraw, lbg) |
| 4604 |
} else { |
| 4605 |
t.markOtherLine(actualLineNum) |
| 4606 |
} |
| 4607 |
lineNum += 1 |
| 4608 |
} |
| 4609 |
|
| 4610 |
return finalLineNum |
| 4611 |
} |
| 4612 |
|
| 4613 |
func (t *Terminal) printColoredString(window tui.Window, text []rune, offsets []colorOffset, colBase tui.ColorPair, initialPrefixWidth ...int) { |
| 4614 |
var index int32 |
| 4615 |
var substr string |
| 4616 |
var prefixWidth int |
| 4617 |
if len(initialPrefixWidth) > 0 { |
| 4618 |
prefixWidth = initialPrefixWidth[0] |
| 4619 |
} |
| 4620 |
maxOffset := int32(len(text)) |
| 4621 |
var url *url |
| 4622 |
for _, offset := range offsets { |
| 4623 |
b := util.Constrain(offset.offset[0], index, maxOffset) |
| 4624 |
e := util.Constrain(offset.offset[1], index, maxOffset) |
| 4625 |
if url != nil && offset.url != url { |
| 4626 |
url = nil |
| 4627 |
window.LinkEnd() |
| 4628 |
} |
| 4629 |
|
| 4630 |
substr, prefixWidth = t.processTabs(text[index:b], prefixWidth) |
| 4631 |
window.CPrint(colBase, substr) |
| 4632 |
|
| 4633 |
if b < e { |
| 4634 |
substr, prefixWidth = t.processTabs(text[b:e], prefixWidth) |
| 4635 |
if url == nil && offset.url != nil { |
| 4636 |
url = offset.url |
| 4637 |
window.LinkBegin(url.uri, url.params) |
| 4638 |
} |
| 4639 |
window.CPrint(offset.color, substr) |
| 4640 |
} |
| 4641 |
|
| 4642 |
index = e |
| 4643 |
if index >= maxOffset { |
| 4644 |
break |
| 4645 |
} |
| 4646 |
} |
| 4647 |
if url != nil { |
| 4648 |
window.LinkEnd() |
| 4649 |
} |
| 4650 |
if index < maxOffset { |
| 4651 |
substr, _ = t.processTabs(text[index:], prefixWidth) |
| 4652 |
window.CPrint(colBase, substr) |
| 4653 |
} |
| 4654 |
} |
| 4655 |
|
| 4656 |
func (t *Terminal) renderPreviewSpinner() { |
| 4657 |
numLines := len(t.previewer.lines) |
| 4658 |
spin := t.previewer.spinner |
| 4659 |
if len(spin) > 0 || t.previewer.scrollable { |
| 4660 |
maxWidth := t.pwindow.Width() |
| 4661 |
if !t.previewer.scrollable || !t.activePreviewOpts.info { |
| 4662 |
if maxWidth > 0 { |
| 4663 |
t.pwindow.Move(0, maxWidth-1) |
| 4664 |
t.pwindow.CPrint(tui.ColPreviewSpinner, spin) |
| 4665 |
} |
| 4666 |
} else { |
| 4667 |
offsetString := fmt.Sprintf("%d/%d", t.previewer.offset+1, numLines) |
| 4668 |
if len(spin) > 0 { |
| 4669 |
spin += " " |
| 4670 |
maxWidth -= 2 |
| 4671 |
} |
| 4672 |
offsetRunes, _ := t.trimRight([]rune(offsetString), maxWidth) |
| 4673 |
pos := maxWidth - t.displayWidth(offsetRunes) |
| 4674 |
t.pwindow.Move(0, pos) |
| 4675 |
if maxWidth > 0 { |
| 4676 |
t.pwindow.CPrint(tui.ColPreviewSpinner, spin) |
| 4677 |
t.pwindow.CPrint(tui.ColInfo.WithAttr(tui.Reverse), string(offsetRunes)) |
| 4678 |
} |
| 4679 |
} |
| 4680 |
} |
| 4681 |
} |
| 4682 |
|
| 4683 |
func (t *Terminal) renderPreviewArea(unchanged bool) { |
| 4684 |
if t.previewed.wipe && t.previewed.version != t.previewer.version { |
| 4685 |
t.previewed.wipe = false |
| 4686 |
t.pwindow.Erase() |
| 4687 |
} else if unchanged { |
| 4688 |
t.pwindow.MoveAndClear(0, 0) // Clear scroll offset display |
| 4689 |
} else { |
| 4690 |
t.previewed.filled = false |
| 4691 |
// We don't erase the window here to avoid flickering during scroll. |
| 4692 |
// However, tcell renderer uses double-buffering technique and there's no |
| 4693 |
// flickering. So we just erase the window and make the rest of the code |
| 4694 |
// simpler. |
| 4695 |
if !t.pwindow.EraseMaybe() { |
| 4696 |
t.pwindow.DrawBorder() |
| 4697 |
t.pwindow.Move(0, 0) |
| 4698 |
} |
| 4699 |
} |
| 4700 |
|
| 4701 |
height := t.pwindow.Height() |
| 4702 |
body := t.previewer.lines |
| 4703 |
headerLines := t.activePreviewOpts.headerLines |
| 4704 |
lineNo := -t.previewer.offset + headerLines |
| 4705 |
// Scrollbar is sized from the body alone, split off or not |
| 4706 |
scrollLines := len(body) |
| 4707 |
// Do not enable preview header lines if it's value is too large |
| 4708 |
if headerLines > 0 && headerLines < min(len(body), height) { |
| 4709 |
scrollLines -= headerLines |
| 4710 |
header := t.previewer.lines[0:headerLines] |
| 4711 |
// A separate header pass would resume the body inside an image, which |
| 4712 |
// takes up more rows than the line it arrives on |
| 4713 |
if !containsImage(header) { |
| 4714 |
// Always redraw header |
| 4715 |
t.renderPreviewText(height, header, 0, false) |
| 4716 |
t.pwindow.MoveAndClear(t.pwindow.Y(), 0) |
| 4717 |
body = t.previewer.lines[headerLines:] |
| 4718 |
} |
| 4719 |
} |
| 4720 |
t.renderPreviewText(height, body, lineNo, unchanged) |
| 4721 |
|
| 4722 |
if !unchanged { |
| 4723 |
t.pwindow.FinishFill() |
| 4724 |
} |
| 4725 |
|
| 4726 |
if len(t.scrollbar) == 0 { |
| 4727 |
return |
| 4728 |
} |
| 4729 |
|
| 4730 |
effectiveHeight := height - headerLines |
| 4731 |
barLength, barStart := getScrollbar(1, scrollLines, effectiveHeight, min(scrollLines-effectiveHeight, t.previewer.offset-headerLines)) |
| 4732 |
t.renderPreviewScrollbar(headerLines, barLength, barStart) |
| 4733 |
} |
| 4734 |
|
| 4735 |
func (t *Terminal) makeImageBorder(width int, top bool) string { |
| 4736 |
tl := "┌" |
| 4737 |
tr := "┐" |
| 4738 |
v := "╎" |
| 4739 |
h := "╌" |
| 4740 |
if !t.unicode { |
| 4741 |
tl = "+" |
| 4742 |
tr = "+" |
| 4743 |
h = "-" |
| 4744 |
v = "|" |
| 4745 |
} |
| 4746 |
repeat := max(0, width-2) |
| 4747 |
if top { |
| 4748 |
return tl + strings.Repeat(h, repeat) + tr |
| 4749 |
} |
| 4750 |
return v + strings.Repeat(" ", repeat) + v |
| 4751 |
} |
| 4752 |
|
| 4753 |
func findPassThrough(line string) []int { |
| 4754 |
loc := passThroughBeginRegex.FindStringIndex(line) |
| 4755 |
if loc == nil { |
| 4756 |
return nil |
| 4757 |
} |
| 4758 |
|
| 4759 |
rest := line[loc[0]:] |
| 4760 |
after := line[loc[1]:] |
| 4761 |
if strings.HasPrefix(rest, "\x1bPtmux") { // Tmux |
| 4762 |
eloc := passThroughEndTmuxRegex.FindStringIndex(after) |
| 4763 |
if eloc == nil { |
| 4764 |
return nil |
| 4765 |
} |
| 4766 |
return []int{loc[0], loc[1] + eloc[1]} |
| 4767 |
} else if strings.HasPrefix(rest, "\x1b]1337;") { // iTerm2 |
| 4768 |
index := loc[1] |
| 4769 |
for { |
| 4770 |
after := line[index:] |
| 4771 |
pos := strings.IndexAny(after, "\x1b\a") |
| 4772 |
if pos < 0 { |
| 4773 |
return nil |
| 4774 |
} |
| 4775 |
if after[pos] == '\a' { |
| 4776 |
return []int{loc[0], index + pos + 1} |
| 4777 |
} |
| 4778 |
if pos < len(after)-1 && after[pos+1] == '\\' { |
| 4779 |
return []int{loc[0], index + pos + 2} |
| 4780 |
} |
| 4781 |
index += pos + 1 |
| 4782 |
} |
| 4783 |
} |
| 4784 |
// Kitty |
| 4785 |
pos := strings.Index(after, "\x1b\\") |
| 4786 |
if pos < 0 { |
| 4787 |
return nil |
| 4788 |
} |
| 4789 |
if pos < len(after)-2 && after[pos+2] == '\r' { |
| 4790 |
return []int{loc[0], loc[1] + pos + 3} |
| 4791 |
} |
| 4792 |
return []int{loc[0], loc[1] + pos + 2} |
| 4793 |
} |
| 4794 |
|
| 4795 |
// tmux takes a bare APC as a request to set the pane title, so a Kitty |
| 4796 |
// graphics command never reaches the terminal and clobbers the title on the |
| 4797 |
// way. 'kitten icat --clear' emits one unwrapped. Sixel is left alone. |
| 4798 |
// https://github.com/junegunn/fzf/issues/4870 |
| 4799 |
func wrapPassThrough(passThrough string, tmux bool) string { |
| 4800 |
if !tmux || !strings.HasPrefix(passThrough, "\x1b_G") { |
| 4801 |
return passThrough |
| 4802 |
} |
| 4803 |
// Only the sequence is passed through, not the trailing CR |
| 4804 |
suffix := "" |
| 4805 |
if strings.HasSuffix(passThrough, "\r") { |
| 4806 |
passThrough, suffix = passThrough[:len(passThrough)-1], "\r" |
| 4807 |
} |
| 4808 |
return "\x1bPtmux;" + strings.ReplaceAll(passThrough, "\x1b", "\x1b\x1b") + "\x1b\\" + suffix |
| 4809 |
} |
| 4810 |
|
| 4811 |
// Whether the sequence draws an image. Kitty commands that only transmit or |
| 4812 |
// delete do not |
| 4813 |
func isImagePassThrough(passThrough string) bool { |
| 4814 |
// Unwrap the tmux passthrough sequence, in which every ESC is doubled |
| 4815 |
if after, ok := strings.CutPrefix(passThrough, "\x1bPtmux;"); ok { |
| 4816 |
passThrough = strings.ReplaceAll(after, "\x1b\x1b", "\x1b") |
| 4817 |
} |
| 4818 |
if after, ok := strings.CutPrefix(passThrough, "\x1b_G"); ok { |
| 4819 |
// Control data ends at the payload delimiter or at the terminator |
| 4820 |
keys := after |
| 4821 |
if index := strings.IndexAny(keys, ";\x1b"); index >= 0 { |
| 4822 |
keys = keys[:index] |
| 4823 |
} |
| 4824 |
for _, key := range strings.Split(keys, ",") { |
| 4825 |
// Transmit and display, or put an image already transmitted |
| 4826 |
if key == "a=T" || key == "a=p" { |
| 4827 |
return true |
| 4828 |
} |
| 4829 |
} |
| 4830 |
return false |
| 4831 |
} |
| 4832 |
if after, ok := strings.CutPrefix(passThrough, "\x1b]1337;"); ok { |
| 4833 |
return strings.HasPrefix(after, "File=") || strings.HasPrefix(after, "MultipartFile=") |
| 4834 |
} |
| 4835 |
return sixelBeginRegex.MatchString(passThrough) |
| 4836 |
} |
| 4837 |
|
| 4838 |
// Whether any line carries an image |
| 4839 |
func containsImage(lines []string) bool { |
| 4840 |
for _, line := range lines { |
| 4841 |
for { |
| 4842 |
loc := findPassThrough(line) |
| 4843 |
if loc == nil { |
| 4844 |
break |
| 4845 |
} |
| 4846 |
if isImagePassThrough(line[loc[0]:loc[1]]) { |
| 4847 |
return true |
| 4848 |
} |
| 4849 |
line = line[loc[1]:] |
| 4850 |
} |
| 4851 |
} |
| 4852 |
return false |
| 4853 |
} |
| 4854 |
|
| 4855 |
func extractPassThroughs(line string) ([]string, string) { |
| 4856 |
passThroughs := []string{} |
| 4857 |
transformed := "" |
| 4858 |
index := 0 |
| 4859 |
for { |
| 4860 |
rest := line[index:] |
| 4861 |
loc := findPassThrough(rest) |
| 4862 |
if loc == nil { |
| 4863 |
transformed += rest |
| 4864 |
break |
| 4865 |
} |
| 4866 |
passThroughs = append(passThroughs, rest[loc[0]:loc[1]]) |
| 4867 |
transformed += line[index : index+loc[0]] |
| 4868 |
index += loc[1] |
| 4869 |
} |
| 4870 |
|
| 4871 |
return passThroughs, transformed |
| 4872 |
} |
| 4873 |
|
| 4874 |
// splitOnIND breaks a preview line on IND (ESC D), which moves the cursor |
| 4875 |
// down one line, keeping the column. A program drawing at a column offset ends |
| 4876 |
// its rows with IND instead of a newline, because ONLCR would rewrite a newline |
| 4877 |
// as CR NL and snap the cursor to column 0. chafa does this for Kitty Unicode |
| 4878 |
// placeholders, and without the break the whole image collapses into a single |
| 4879 |
// line. |
| 4880 |
// |
| 4881 |
// The column is tracked and re-created with padding so that an indented image |
| 4882 |
// keeps its indent, and a CUB right before the IND is subtracted, which is how |
| 4883 |
// chafa returns to the column its rows start on. |
| 4884 |
func (t *Terminal) splitOnIND(line string) []string { |
| 4885 |
chunks := strings.Split(line, "\x1bD") |
| 4886 |
if len(chunks) == 1 { |
| 4887 |
return nil |
| 4888 |
} |
| 4889 |
|
| 4890 |
lines := make([]string, 0, len(chunks)) |
| 4891 |
col := 0 |
| 4892 |
for _, chunk := range chunks[:len(chunks)-1] { |
| 4893 |
lines = append(lines, strings.Repeat(" ", col)+chunk+"\n") |
| 4894 |
col += t.displayWidthWithoutEscapes(chunk, col) |
| 4895 |
if match := cursorBackRegex.FindStringSubmatch(chunk); match != nil { |
| 4896 |
back := 1 |
| 4897 |
if len(match[1]) > 0 { |
| 4898 |
back, _ = strconv.Atoi(match[1]) |
| 4899 |
} |
| 4900 |
col = max(0, col-back) |
| 4901 |
} |
| 4902 |
} |
| 4903 |
return append(lines, strings.Repeat(" ", col)+chunks[len(chunks)-1]) |
| 4904 |
} |
| 4905 |
|
| 4906 |
// followOffset computes the correct content-line offset for follow mode, |
| 4907 |
// accounting for line wrapping in the preview window. |
| 4908 |
func (t *Terminal) followOffset() int { |
| 4909 |
lines := t.previewer.lines |
| 4910 |
headerLines := t.activePreviewOpts.headerLines |
| 4911 |
height := t.pwindow.Height() - headerLines |
| 4912 |
if height <= 0 || len(lines) <= headerLines { |
| 4913 |
return headerLines |
| 4914 |
} |
| 4915 |
|
| 4916 |
body := lines[headerLines:] |
| 4917 |
if !t.activePreviewOpts.wrap { |
| 4918 |
return max(t.previewer.offset, headerLines+len(body)-height) |
| 4919 |
} |
| 4920 |
|
| 4921 |
maxWidth := t.pwindow.Width() |
| 4922 |
visualLines := 0 |
| 4923 |
for i := len(body) - 1; i >= 0; i-- { |
| 4924 |
h := t.previewLineHeight(body[i], maxWidth) |
| 4925 |
if visualLines+h > height { |
| 4926 |
return min(len(lines)-1, headerLines+i+1) |
| 4927 |
} |
| 4928 |
visualLines += h |
| 4929 |
} |
| 4930 |
return headerLines |
| 4931 |
} |
| 4932 |
|
| 4933 |
// previewLineHeight estimates the number of visual lines a preview content line |
| 4934 |
// occupies when wrapping is enabled. |
| 4935 |
func (t *Terminal) previewLineHeight(line string, maxWidth int) int { |
| 4936 |
if maxWidth <= 0 { |
| 4937 |
return 1 |
| 4938 |
} |
| 4939 |
|
| 4940 |
// For word-wrap mode, count the sub-lines produced by word wrapping. |
| 4941 |
// Each sub-line may still char-wrap if it contains a word longer than the width. |
| 4942 |
if t.activePreviewOpts.wrapWord { |
| 4943 |
subLines := t.wordWrapAnsiLine(line, maxWidth, t.previewWrapSignWidth) |
| 4944 |
total := 0 |
| 4945 |
for i, sub := range subLines { |
| 4946 |
prefixWidth := 0 |
| 4947 |
cols := maxWidth |
| 4948 |
if i > 0 { |
| 4949 |
prefixWidth = t.previewWrapSignWidth |
| 4950 |
cols -= t.previewWrapSignWidth |
| 4951 |
} |
| 4952 |
w := t.ansiLineWidth(sub, prefixWidth) |
| 4953 |
if cols <= 0 { |
| 4954 |
cols = 1 |
| 4955 |
} |
| 4956 |
total += max(1, (w+cols-1)/cols) |
| 4957 |
} |
| 4958 |
return total |
| 4959 |
} |
| 4960 |
|
| 4961 |
// For char-wrap, compute visible width and divide by available width. |
| 4962 |
w := t.ansiLineWidth(line, 0) |
| 4963 |
if w <= maxWidth { |
| 4964 |
return 1 |
| 4965 |
} |
| 4966 |
remaining := w - maxWidth |
| 4967 |
contWidth := max(1, maxWidth-t.previewWrapSignWidth) |
| 4968 |
return 1 + (remaining+contWidth-1)/contWidth |
| 4969 |
} |
| 4970 |
|
| 4971 |
// ansiLineWidth computes the display width of a string, skipping ANSI escape sequences. |
| 4972 |
// prefixWidth is the visual offset where the content starts (e.g. wrap sign width for |
| 4973 |
// continuation lines), used for correct tab stop alignment. |
| 4974 |
func (t *Terminal) ansiLineWidth(line string, prefixWidth int) int { |
| 4975 |
line = strings.TrimSuffix(line, "\n") |
| 4976 |
trimmed, _, _ := extractColor(line, nil, nil) |
| 4977 |
_, width := t.processTabsStr(trimmed, prefixWidth) |
| 4978 |
return width - prefixWidth |
| 4979 |
} |
| 4980 |
|
| 4981 |
func (t *Terminal) wordWrapAnsiLine(line string, maxWidth int, wrapSignWidth int) []string { |
| 4982 |
if maxWidth <= 0 { |
| 4983 |
return []string{line} |
| 4984 |
} |
| 4985 |
|
| 4986 |
var result []string |
| 4987 |
lineStart := 0 |
| 4988 |
width := 0 |
| 4989 |
lastSpaceStart := -1 |
| 4990 |
lastSpaceEnd := -1 |
| 4991 |
widthBeforeLastSpace := 0 |
| 4992 |
lastSpaceWidth := 0 |
| 4993 |
max := maxWidth |
| 4994 |
pos := 0 |
| 4995 |
|
| 4996 |
for pos < len(line) { |
| 4997 |
// Find next ANSI escape sequence |
| 4998 |
start, end := nextAnsiEscapeSequence(line[pos:]) |
| 4999 |
|
| 5000 |
// Determine the end of printable text before the next escape |
| 5001 |
var printableEnd int |
| 5002 |
if start < 0 { |
| 5003 |
printableEnd = len(line) |
| 5004 |
} else { |
| 5005 |
printableEnd = pos + start |
| 5006 |
} |
| 5007 |
|
| 5008 |
// Process printable characters using grapheme clusters |
| 5009 |
gr := uniseg.NewGraphemes(line[pos:printableEnd]) |
| 5010 |
for gr.Next() { |
| 5011 |
gStart, gEnd := gr.Positions() |
| 5012 |
w := gr.Width() |
| 5013 |
str := gr.Str() |
| 5014 |
|
| 5015 |
if str == "\t" { |
| 5016 |
w = t.tabstop - (width % t.tabstop) |
| 5017 |
} |
| 5018 |
|
| 5019 |
if str == " " || str == "\t" { |
| 5020 |
lastSpaceStart = pos + gStart |
| 5021 |
lastSpaceEnd = pos + gEnd |
| 5022 |
widthBeforeLastSpace = width |
| 5023 |
lastSpaceWidth = w |
| 5024 |
} |
| 5025 |
|
| 5026 |
width += w |
| 5027 |
|
| 5028 |
if width > max && lastSpaceEnd > lineStart { |
| 5029 |
result = append(result, line[lineStart:lastSpaceStart]) |
| 5030 |
lineStart = lastSpaceEnd |
| 5031 |
width -= widthBeforeLastSpace + lastSpaceWidth |
| 5032 |
lastSpaceStart = -1 |
| 5033 |
lastSpaceEnd = -1 |
| 5034 |
widthBeforeLastSpace = 0 |
| 5035 |
max = maxWidth - wrapSignWidth |
| 5036 |
} |
| 5037 |
} |
| 5038 |
pos = printableEnd |
| 5039 |
|
| 5040 |
// Skip the ANSI escape sequence |
| 5041 |
if start >= 0 { |
| 5042 |
pos += end - start |
| 5043 |
} |
| 5044 |
} |
| 5045 |
|
| 5046 |
result = append(result, line[lineStart:]) |
| 5047 |
return result |
| 5048 |
} |
| 5049 |
|
| 5050 |
func (t *Terminal) renderPreviewText(height int, lines []string, lineNo int, unchanged bool) { |
| 5051 |
maxWidth := t.pwindow.Width() |
| 5052 |
var ansi *ansiState |
| 5053 |
spinnerRedraw := t.pwindow.Y() == 0 |
| 5054 |
wiped := false |
| 5055 |
image := false |
| 5056 |
wireframe := false |
| 5057 |
var index int |
| 5058 |
var line string |
| 5059 |
Loop: |
| 5060 |
for index, line = range lines { |
| 5061 |
var lbg tui.Color = -1 |
| 5062 |
if ansi != nil { |
| 5063 |
ansi.lbg = -1 |
| 5064 |
} |
| 5065 |
|
| 5066 |
passThroughs, line := extractPassThroughs(line) |
| 5067 |
line = strings.TrimLeft(strings.TrimRight(line, "\r\n"), "\r") |
| 5068 |
|
| 5069 |
if lineNo >= height || t.pwindow.Y() == height-1 && t.pwindow.X() > 0 { |
| 5070 |
t.previewed.filled = true |
| 5071 |
t.previewer.scrollable = true |
| 5072 |
break |
| 5073 |
} else if lineNo >= 0 { |
| 5074 |
x := t.pwindow.X() |
| 5075 |
y := t.pwindow.Y() |
| 5076 |
if spinnerRedraw && lineNo > 0 { |
| 5077 |
spinnerRedraw = false |
| 5078 |
t.renderPreviewSpinner() |
| 5079 |
t.pwindow.Move(y, x) |
| 5080 |
} |
| 5081 |
for idx, passThrough := range passThroughs { |
| 5082 |
// Handling Sixel/iTerm image |
| 5083 |
requiredLines := 0 |
| 5084 |
isSixel := strings.HasPrefix(passThrough, "\x1bP") |
| 5085 |
isItermImage := strings.HasPrefix(passThrough, "\x1b]1337;") |
| 5086 |
isImage := isSixel || isItermImage |
| 5087 |
if isImage { |
| 5088 |
t.previewed.wipe = true |
| 5089 |
// NOTE: We don't have a good way to get the height of an iTerm image, |
| 5090 |
// so we assume that it requires the full height of the preview |
| 5091 |
// window. |
| 5092 |
requiredLines = height |
| 5093 |
|
| 5094 |
if isSixel && t.termSize.PxHeight > 0 { |
| 5095 |
rows := strings.Count(passThrough, "-") |
| 5096 |
requiredLines = int(math.Ceil(float64(rows*6*t.termSize.Lines) / float64(t.termSize.PxHeight))) |
| 5097 |
} |
| 5098 |
} |
| 5099 |
|
| 5100 |
// Render wireframe when the image cannot be displayed entirely |
| 5101 |
if requiredLines > 0 && y+requiredLines > height { |
| 5102 |
top := true |
| 5103 |
for ; y < height; y++ { |
| 5104 |
t.pwindow.MoveAndClear(y, 0) |
| 5105 |
t.pwindow.CFill(tui.ColPreview.Fg(), tui.ColPreview.Bg(), -1, tui.AttrRegular, t.makeImageBorder(maxWidth, top)) |
| 5106 |
top = false |
| 5107 |
} |
| 5108 |
wireframe = true |
| 5109 |
t.previewed.filled = true |
| 5110 |
t.previewer.scrollable = true |
| 5111 |
break Loop |
| 5112 |
} |
| 5113 |
|
| 5114 |
// Clear previous wireframe or any other text |
| 5115 |
if (t.previewed.wireframe || isImage && !t.previewed.image) && !wiped { |
| 5116 |
wiped = true |
| 5117 |
for i := y + 1; i < height; i++ { |
| 5118 |
t.pwindow.MoveAndClear(i, 0) |
| 5119 |
} |
| 5120 |
} |
| 5121 |
image = image || isImage |
| 5122 |
if idx == 0 { |
| 5123 |
t.pwindow.MoveAndClear(y, x) |
| 5124 |
} else { |
| 5125 |
t.pwindow.Move(y, x) |
| 5126 |
} |
| 5127 |
t.tui.PassThrough(wrapPassThrough(passThrough, inTmux)) |
| 5128 |
|
| 5129 |
if requiredLines > 0 { |
| 5130 |
if y+requiredLines == height { |
| 5131 |
t.pwindow.Move(height-1, maxWidth-1) |
| 5132 |
t.previewed.filled = true |
| 5133 |
break Loop |
| 5134 |
} |
| 5135 |
t.pwindow.MoveAndClear(y+requiredLines, 0) |
| 5136 |
} |
| 5137 |
} |
| 5138 |
|
| 5139 |
if len(passThroughs) > 0 && len(line) == 0 { |
| 5140 |
continue |
| 5141 |
} |
| 5142 |
|
| 5143 |
// Pre-split line into sub-lines for word wrapping |
| 5144 |
var subLines []string |
| 5145 |
if t.activePreviewOpts.wrapWord { |
| 5146 |
subLines = t.wordWrapAnsiLine(line, maxWidth, t.previewWrapSignWidth) |
| 5147 |
} else { |
| 5148 |
subLines = []string{line} |
| 5149 |
} |
| 5150 |
|
| 5151 |
var fillRet tui.FillReturn |
| 5152 |
wrap := t.activePreviewOpts.wrap |
| 5153 |
printWrapSign := func() { |
| 5154 |
if t.pwindow.CFill(tui.ColPreview.Fg(), tui.ColPreview.Bg(), -1, tui.Dim, t.previewWrapSign) == tui.FillNextLine { |
| 5155 |
t.pwindow.Move(t.pwindow.Y()-1, t.pwindow.Width()) |
| 5156 |
} |
| 5157 |
fillRet = tui.FillContinue |
| 5158 |
} |
| 5159 |
for subIdx, subLine := range subLines { |
| 5160 |
// Render wrap sign for continuation sub-lines |
| 5161 |
if subIdx > 0 { |
| 5162 |
if fillRet == tui.FillContinue { |
| 5163 |
fillRet = t.pwindow.Fill("\n") |
| 5164 |
if fillRet == tui.FillSuspend { |
| 5165 |
t.previewed.filled = true |
| 5166 |
break Loop |
| 5167 |
} |
| 5168 |
} |
| 5169 |
printWrapSign() |
| 5170 |
} |
| 5171 |
|
| 5172 |
prefixWidth := t.pwindow.X() |
| 5173 |
var url *url |
| 5174 |
_, _, ansi = extractColor(subLine, ansi, func(str string, ansi *ansiState) bool { |
| 5175 |
if len(str) > 0 && fillRet == tui.FillNextLine { |
| 5176 |
printWrapSign() |
| 5177 |
prefixWidth = t.pwindow.X() |
| 5178 |
} |
| 5179 |
trimmed := []rune(str) |
| 5180 |
isTrimmed := false |
| 5181 |
if !wrap { |
| 5182 |
trimmed, isTrimmed = t.trimRight(trimmed, maxWidth-t.pwindow.X()) |
| 5183 |
} |
| 5184 |
if url == nil && ansi != nil && ansi.url != nil { |
| 5185 |
url = ansi.url |
| 5186 |
t.pwindow.LinkBegin(url.uri, url.params) |
| 5187 |
} |
| 5188 |
if url != nil && (ansi == nil || ansi.url == nil) { |
| 5189 |
url = nil |
| 5190 |
t.pwindow.LinkEnd() |
| 5191 |
} |
| 5192 |
if ansi != nil { |
| 5193 |
lbg = ansi.lbg |
| 5194 |
} else { |
| 5195 |
lbg = -1 |
| 5196 |
} |
| 5197 |
str, width := t.processTabs(trimmed, prefixWidth) |
| 5198 |
if width > prefixWidth { |
| 5199 |
prefixWidth = width |
| 5200 |
colored := ansi != nil && ansi.colored() |
| 5201 |
if t.theme.Colored && colored { |
| 5202 |
fillRet = t.pwindow.CFill(ansi.fg, ansi.bg, ansi.ul, ansi.attr, str) |
| 5203 |
} else { |
| 5204 |
attr := tui.AttrRegular |
| 5205 |
if colored { |
| 5206 |
attr = ansi.attr |
| 5207 |
} |
| 5208 |
fillRet = t.pwindow.CFill(tui.ColPreview.Fg(), tui.ColPreview.Bg(), -1, attr, str) |
| 5209 |
} |
| 5210 |
} |
| 5211 |
return !isTrimmed && |
| 5212 |
(fillRet == tui.FillContinue || wrap && fillRet == tui.FillNextLine) |
| 5213 |
}) |
| 5214 |
if url != nil { |
| 5215 |
t.pwindow.LinkEnd() |
| 5216 |
} |
| 5217 |
|
| 5218 |
if fillRet == tui.FillSuspend { |
| 5219 |
t.previewed.filled = true |
| 5220 |
break Loop |
| 5221 |
} |
| 5222 |
} |
| 5223 |
|
| 5224 |
t.previewer.scrollable = t.previewer.scrollable || t.pwindow.Y() == height-1 && t.pwindow.X() == t.pwindow.Width() || t.previewed.filled |
| 5225 |
if fillRet == tui.FillNextLine { |
| 5226 |
continue |
| 5227 |
} else if fillRet == tui.FillSuspend { |
| 5228 |
t.previewed.filled = true |
| 5229 |
break |
| 5230 |
} |
| 5231 |
if unchanged && lineNo == 0 { |
| 5232 |
break |
| 5233 |
} |
| 5234 |
if t.theme.Colored && lbg >= 0 { |
| 5235 |
fillRet = t.pwindow.CFill(-1, lbg, -1, tui.AttrRegular, |
| 5236 |
strings.Repeat(" ", t.pwindow.Width()-t.pwindow.X())+"\n") |
| 5237 |
} else { |
| 5238 |
fillRet = t.pwindow.Fill("\n") |
| 5239 |
} |
| 5240 |
if fillRet == tui.FillSuspend { |
| 5241 |
t.previewed.filled = true |
| 5242 |
break |
| 5243 |
} |
| 5244 |
} |
| 5245 |
lineNo++ |
| 5246 |
} |
| 5247 |
t.previewer.scrollable = t.previewer.scrollable || t.previewed.filled || index < len(lines)-1 |
| 5248 |
t.previewed.image = image |
| 5249 |
t.previewed.wireframe = wireframe |
| 5250 |
} |
| 5251 |
|
| 5252 |
func (t *Terminal) renderPreviewScrollbar(yoff int, barLength int, barStart int) { |
| 5253 |
height := t.pwindow.Height() |
| 5254 |
w := t.pborder.Width() |
| 5255 |
xw := [2]int{t.pwindow.Left(), t.pwindow.Width()} |
| 5256 |
redraw := false |
| 5257 |
if len(t.previewer.bar) != height || t.previewer.xw != xw || t.previewed.version != t.previewer.version { |
| 5258 |
redraw = true |
| 5259 |
t.previewer.bar = make([]bool, height) |
| 5260 |
t.previewer.xw = xw |
| 5261 |
} |
| 5262 |
xshift := -1 - t.borderWidth |
| 5263 |
if !t.activePreviewOpts.Border(t.layout).HasRight() { |
| 5264 |
xshift = -1 |
| 5265 |
} |
| 5266 |
yshift := 1 |
| 5267 |
if !t.activePreviewOpts.Border(t.layout).HasTop() { |
| 5268 |
yshift = 0 |
| 5269 |
} |
| 5270 |
for i := yoff; i < height; i++ { |
| 5271 |
x := w + xshift |
| 5272 |
y := i + yshift |
| 5273 |
|
| 5274 |
// Avoid unnecessary redraws |
| 5275 |
bar := i >= yoff+barStart && i < yoff+barStart+barLength |
| 5276 |
if !redraw && bar == t.previewer.bar[i] && !t.tui.NeedScrollbarRedraw() { |
| 5277 |
continue |
| 5278 |
} |
| 5279 |
|
| 5280 |
t.previewer.bar[i] = bar |
| 5281 |
t.pborder.Move(y, x) |
| 5282 |
if i >= yoff+barStart && i < yoff+barStart+barLength { |
| 5283 |
t.pborder.CPrint(tui.ColPreviewScrollbar, t.previewScrollbar) |
| 5284 |
} else { |
| 5285 |
t.pborder.CPrint(tui.ColPreviewScrollbar, " ") |
| 5286 |
} |
| 5287 |
} |
| 5288 |
} |
| 5289 |
|
| 5290 |
func (t *Terminal) printPreview() { |
| 5291 |
if !t.hasPreviewWindow() || t.pwindow.Height() == 0 { |
| 5292 |
return |
| 5293 |
} |
| 5294 |
numLines := len(t.previewer.lines) |
| 5295 |
height := t.pwindow.Height() |
| 5296 |
unchanged := (t.previewed.filled || numLines == t.previewed.numLines) && |
| 5297 |
t.previewer.version == t.previewed.version && |
| 5298 |
t.previewer.offset == t.previewed.offset |
| 5299 |
t.previewer.scrollable = t.previewer.offset > t.activePreviewOpts.headerLines || numLines > height |
| 5300 |
t.renderPreviewArea(unchanged) |
| 5301 |
t.renderPreviewSpinner() |
| 5302 |
t.previewed.numLines = numLines |
| 5303 |
t.previewed.version = t.previewer.version |
| 5304 |
t.previewed.offset = t.previewer.offset |
| 5305 |
} |
| 5306 |
|
| 5307 |
func (t *Terminal) printPreviewDelayed() { |
| 5308 |
if !t.hasPreviewWindow() || len(t.previewer.lines) > 0 && t.previewed.version == t.previewer.version { |
| 5309 |
return |
| 5310 |
} |
| 5311 |
|
| 5312 |
t.previewer.scrollable = false |
| 5313 |
t.renderPreviewArea(true) |
| 5314 |
|
| 5315 |
message := t.trimMessage("Loading ..", t.pwindow.Width()) |
| 5316 |
pos := t.pwindow.Width() - len(message) |
| 5317 |
t.pwindow.Move(0, pos) |
| 5318 |
t.pwindow.CPrint(tui.ColInfo.WithAttr(tui.Reverse), message) |
| 5319 |
} |
| 5320 |
|
| 5321 |
func (t *Terminal) processTabsStr(input string, prefixWidth int) (string, int) { |
| 5322 |
var strbuf strings.Builder |
| 5323 |
l := prefixWidth |
| 5324 |
gr := uniseg.NewGraphemes(input) |
| 5325 |
for gr.Next() { |
| 5326 |
rs := gr.Runes() |
| 5327 |
str := string(rs) |
| 5328 |
var w int |
| 5329 |
if len(rs) == 1 && rs[0] == '\t' { |
| 5330 |
w = t.tabstop - l%t.tabstop |
| 5331 |
strbuf.WriteString(strings.Repeat(" ", w)) |
| 5332 |
} else { |
| 5333 |
w = util.StringWidth(str) |
| 5334 |
strbuf.WriteString(str) |
| 5335 |
} |
| 5336 |
l += w |
| 5337 |
} |
| 5338 |
return strbuf.String(), l |
| 5339 |
} |
| 5340 |
|
| 5341 |
func (t *Terminal) processTabs(runes []rune, prefixWidth int) (string, int) { |
| 5342 |
return t.processTabsStr(string(runes), prefixWidth) |
| 5343 |
} |
| 5344 |
|
| 5345 |
func (t *Terminal) printAll() { |
| 5346 |
t.resizeWindows(t.forcePreview, true) |
| 5347 |
t.printList() |
| 5348 |
t.printPrompt() |
| 5349 |
t.printInfo() |
| 5350 |
t.printHeader() |
| 5351 |
t.printFooter() |
| 5352 |
t.printPreview() |
| 5353 |
} |
| 5354 |
|
| 5355 |
func (t *Terminal) flush() { |
| 5356 |
t.placeCursor() |
| 5357 |
if !t.suppress { |
| 5358 |
windows := make([]tui.Window, 0, 9) |
| 5359 |
if t.border != nil { |
| 5360 |
windows = append(windows, t.border) |
| 5361 |
} |
| 5362 |
if t.pborder != nil { |
| 5363 |
windows = append(windows, t.pborder) |
| 5364 |
} |
| 5365 |
if t.pwindow != nil { |
| 5366 |
windows = append(windows, t.pwindow) |
| 5367 |
} |
| 5368 |
if t.wborder != nil { |
| 5369 |
windows = append(windows, t.wborder) |
| 5370 |
} |
| 5371 |
if t.window != nil { |
| 5372 |
windows = append(windows, t.window) |
| 5373 |
} |
| 5374 |
if t.headerBorder != nil { |
| 5375 |
windows = append(windows, t.headerBorder) |
| 5376 |
} |
| 5377 |
if t.headerWindow != nil { |
| 5378 |
windows = append(windows, t.headerWindow) |
| 5379 |
} |
| 5380 |
if t.headerLinesBorder != nil { |
| 5381 |
windows = append(windows, t.headerLinesBorder) |
| 5382 |
} |
| 5383 |
if t.headerLinesWindow != nil { |
| 5384 |
windows = append(windows, t.headerLinesWindow) |
| 5385 |
} |
| 5386 |
if t.inputBorder != nil { |
| 5387 |
windows = append(windows, t.inputBorder) |
| 5388 |
} |
| 5389 |
if t.inputWindow != nil { |
| 5390 |
windows = append(windows, t.inputWindow) |
| 5391 |
} |
| 5392 |
t.tui.RefreshWindows(windows) |
| 5393 |
} |
| 5394 |
} |
| 5395 |
|
| 5396 |
func (t *Terminal) delChar() bool { |
| 5397 |
if len(t.input) > 0 && t.cx < len(t.input) { |
| 5398 |
t.input = append(t.input[:t.cx], t.input[t.cx+1:]...) |
| 5399 |
return true |
| 5400 |
} |
| 5401 |
return false |
| 5402 |
} |
| 5403 |
|
| 5404 |
func findLastMatch(pattern string, str string) int { |
| 5405 |
rx, err := regexp.Compile(pattern) |
| 5406 |
if err != nil { |
| 5407 |
return -1 |
| 5408 |
} |
| 5409 |
locs := rx.FindAllStringIndex(str, -1) |
| 5410 |
if locs == nil { |
| 5411 |
return -1 |
| 5412 |
} |
| 5413 |
prefix := []rune(str[:locs[len(locs)-1][0]]) |
| 5414 |
return len(prefix) |
| 5415 |
} |
| 5416 |
|
| 5417 |
func findFirstMatch(pattern string, str string) int { |
| 5418 |
rx, err := regexp.Compile(pattern) |
| 5419 |
if err != nil { |
| 5420 |
return -1 |
| 5421 |
} |
| 5422 |
loc := rx.FindStringIndex(str) |
| 5423 |
if loc == nil { |
| 5424 |
return -1 |
| 5425 |
} |
| 5426 |
prefix := []rune(str[:loc[0]]) |
| 5427 |
return len(prefix) |
| 5428 |
} |
| 5429 |
|
| 5430 |
func copySlice(slice []rune) []rune { |
| 5431 |
ret := make([]rune, len(slice)) |
| 5432 |
copy(ret, slice) |
| 5433 |
return ret |
| 5434 |
} |
| 5435 |
|
| 5436 |
func (t *Terminal) rubout(pattern string) { |
| 5437 |
pcx := t.cx |
| 5438 |
after := t.input[t.cx:] |
| 5439 |
t.cx = findLastMatch(pattern, string(t.input[:t.cx])) + 1 |
| 5440 |
t.yanked = copySlice(t.input[t.cx:pcx]) |
| 5441 |
t.input = append(t.input[:t.cx], after...) |
| 5442 |
} |
| 5443 |
|
| 5444 |
func keyMatch(key tui.Event, event tui.Event) bool { |
| 5445 |
return event.Type == key.Type && event.Char == key.Char || |
| 5446 |
key.Type == tui.DoubleClick && event.Type == tui.Mouse && event.MouseEvent.Double |
| 5447 |
} |
| 5448 |
|
| 5449 |
func parsePlaceholder(match string) (bool, string, placeholderFlags) { |
| 5450 |
flags := placeholderFlags{} |
| 5451 |
|
| 5452 |
if match[0] == '\\' { |
| 5453 |
// Escaped placeholder pattern |
| 5454 |
return true, match[1:], flags |
| 5455 |
} |
| 5456 |
|
| 5457 |
if strings.HasPrefix(match, "{fzf:") { |
| 5458 |
// {fzf:*} are not determined by the current item |
| 5459 |
flags.forceUpdate = true |
| 5460 |
return false, match, flags |
| 5461 |
} |
| 5462 |
|
| 5463 |
trimmed := "" |
| 5464 |
for _, char := range match[1:] { |
| 5465 |
switch char { |
| 5466 |
case '*': |
| 5467 |
flags.asterisk = true |
| 5468 |
case '+': |
| 5469 |
flags.plus = true |
| 5470 |
case 's': |
| 5471 |
flags.preserveSpace = true |
| 5472 |
case 'n': |
| 5473 |
flags.number = true |
| 5474 |
case 'f': |
| 5475 |
flags.file = true |
| 5476 |
case 'r': |
| 5477 |
flags.raw = true |
| 5478 |
case 'q': |
| 5479 |
flags.forceUpdate = true |
| 5480 |
trimmed += string(char) |
| 5481 |
default: |
| 5482 |
trimmed += string(char) |
| 5483 |
} |
| 5484 |
} |
| 5485 |
|
| 5486 |
matchWithoutFlags := "{" + trimmed |
| 5487 |
|
| 5488 |
return false, matchWithoutFlags, flags |
| 5489 |
} |
| 5490 |
|
| 5491 |
func hasPreviewFlags(template string) (slot bool, plus bool, asterisk bool, forceUpdate bool) { |
| 5492 |
for _, match := range placeholder.FindAllString(template, -1) { |
| 5493 |
escaped, _, flags := parsePlaceholder(match) |
| 5494 |
if escaped { |
| 5495 |
continue |
| 5496 |
} |
| 5497 |
slot = true |
| 5498 |
plus = plus || flags.plus |
| 5499 |
asterisk = asterisk || flags.asterisk |
| 5500 |
forceUpdate = forceUpdate || flags.forceUpdate |
| 5501 |
} |
| 5502 |
return |
| 5503 |
} |
| 5504 |
|
| 5505 |
type replacePlaceholderParams struct { |
| 5506 |
template string |
| 5507 |
stripAnsi bool |
| 5508 |
delimiter Delimiter |
| 5509 |
printsep string |
| 5510 |
forcePlus bool |
| 5511 |
query string |
| 5512 |
allItems [3][]*Item // current, select, and all matched items |
| 5513 |
lastAction actionType |
| 5514 |
prompt string |
| 5515 |
executor *util.Executor |
| 5516 |
} |
| 5517 |
|
| 5518 |
func (t *Terminal) replacePlaceholderInInitialCommand(template string) (string, []string) { |
| 5519 |
return t.replacePlaceholder(template, false, string(t.input), [3][]*Item{nil, nil, nil}) |
| 5520 |
} |
| 5521 |
|
| 5522 |
func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list [3][]*Item) (string, []string) { |
| 5523 |
return replacePlaceholder(replacePlaceholderParams{ |
| 5524 |
template: template, |
| 5525 |
stripAnsi: t.ansi, |
| 5526 |
delimiter: t.delimiter, |
| 5527 |
printsep: t.printsep, |
| 5528 |
forcePlus: forcePlus, |
| 5529 |
query: input, |
| 5530 |
allItems: list, |
| 5531 |
lastAction: t.lastAction, |
| 5532 |
prompt: t.promptString, |
| 5533 |
executor: t.executor, |
| 5534 |
}) |
| 5535 |
} |
| 5536 |
|
| 5537 |
func (t *Terminal) evaluateScrollOffset() int { |
| 5538 |
if t.pwindow == nil { |
| 5539 |
return 0 |
| 5540 |
} |
| 5541 |
|
| 5542 |
// We only need the current item to calculate the scroll offset |
| 5543 |
current := []*Item{t.currentItem()} |
| 5544 |
if current[0] == nil { |
| 5545 |
current = nil |
| 5546 |
} |
| 5547 |
replaced, tempFiles := t.replacePlaceholder(t.activePreviewOpts.scroll, false, "", [3][]*Item{current, nil, nil}) |
| 5548 |
removeFiles(tempFiles) |
| 5549 |
offsetExpr := offsetTrimCharsRegex.ReplaceAllString(replaced, "") |
| 5550 |
|
| 5551 |
atoi := func(s string) int { |
| 5552 |
n, e := strconv.Atoi(s) |
| 5553 |
if e != nil { |
| 5554 |
return 0 |
| 5555 |
} |
| 5556 |
return n |
| 5557 |
} |
| 5558 |
|
| 5559 |
base := -1 |
| 5560 |
height := max(0, t.pwindow.Height()-t.activePreviewOpts.headerLines) |
| 5561 |
for _, component := range offsetComponentRegex.FindAllString(offsetExpr, -1) { |
| 5562 |
if strings.HasPrefix(component, "-/") { |
| 5563 |
component = component[1:] |
| 5564 |
} |
| 5565 |
if component[0] == '/' { |
| 5566 |
denom := atoi(component[1:]) |
| 5567 |
if denom != 0 { |
| 5568 |
base -= height / denom |
| 5569 |
} |
| 5570 |
break |
| 5571 |
} |
| 5572 |
base += atoi(component) |
| 5573 |
} |
| 5574 |
return max(0, base) |
| 5575 |
} |
| 5576 |
|
| 5577 |
func replacePlaceholder(params replacePlaceholderParams) (string, []string) { |
| 5578 |
tempFiles := []string{} |
| 5579 |
current := params.allItems[0] |
| 5580 |
selected := params.allItems[1] |
| 5581 |
matched := params.allItems[2] |
| 5582 |
|
| 5583 |
// replace placeholders one by one |
| 5584 |
replaced := placeholder.ReplaceAllStringFunc(params.template, func(match string) string { |
| 5585 |
escaped, match, flags := parsePlaceholder(match) |
| 5586 |
|
| 5587 |
// this function implements the effects a placeholder has on items |
| 5588 |
var replace func(*Item) string |
| 5589 |
|
| 5590 |
// placeholder types (escaped, query type, item type, token type) |
| 5591 |
switch { |
| 5592 |
case escaped: |
| 5593 |
return match |
| 5594 |
case match == "{q}" || match == "{fzf:query}": |
| 5595 |
return params.executor.QuoteEntry(params.query) |
| 5596 |
case strings.HasPrefix(match, "{q:"): |
| 5597 |
if nth, err := splitNth(match[3 : len(match)-1]); err == nil { |
| 5598 |
elems, prefixLength := awkTokenizer(params.query) |
| 5599 |
tokens := withPrefixLengths(elems, prefixLength) |
| 5600 |
trans := Transform(tokens, nth) |
| 5601 |
result := JoinTokens(trans) |
| 5602 |
if !flags.preserveSpace { |
| 5603 |
result = strings.TrimSpace(result) |
| 5604 |
} |
| 5605 |
return params.executor.QuoteEntry(result) |
| 5606 |
} |
| 5607 |
|
| 5608 |
return match |
| 5609 |
case match == "{}": |
| 5610 |
replace = func(item *Item) string { |
| 5611 |
switch { |
| 5612 |
case flags.number: |
| 5613 |
n := item.text.Index |
| 5614 |
if n == minItem.Index() { |
| 5615 |
// NOTE: Item index should normally be positive, but if there's no |
| 5616 |
// match, it will be set to math.MinInt32, and we don't want to |
| 5617 |
// show that value. However, int32 can overflow, especially when |
| 5618 |
// `--tail` is used with an endless input stream, and the index of |
| 5619 |
// an item actually can be math.MinInt32. In that case, you're |
| 5620 |
// getting an incorrect value, but we're going to ignore that for |
| 5621 |
// now. |
| 5622 |
return "''" |
| 5623 |
} |
| 5624 |
return strconv.Itoa(int(n)) |
| 5625 |
case flags.file || flags.raw: |
| 5626 |
return item.AsString(params.stripAnsi) |
| 5627 |
default: |
| 5628 |
return params.executor.QuoteEntry(item.AsString(params.stripAnsi)) |
| 5629 |
} |
| 5630 |
} |
| 5631 |
case match == "{fzf:action}": |
| 5632 |
return params.lastAction.Name() |
| 5633 |
case match == "{fzf:prompt}": |
| 5634 |
return params.executor.QuoteEntry(params.prompt) |
| 5635 |
default: |
| 5636 |
// token type and also failover (below) |
| 5637 |
rangeExpressions := strings.Split(match[1:len(match)-1], ",") |
| 5638 |
ranges := make([]Range, len(rangeExpressions)) |
| 5639 |
for idx, s := range rangeExpressions { |
| 5640 |
r, ok := ParseRange(&s) // ellipsis (x..y) and shorthand (x..x) range syntax |
| 5641 |
if !ok { |
| 5642 |
// Invalid expression, just return the original string in the template |
| 5643 |
return match |
| 5644 |
} |
| 5645 |
ranges[idx] = r |
| 5646 |
} |
| 5647 |
|
| 5648 |
replace = func(item *Item) string { |
| 5649 |
tokens := Tokenize(item.AsString(params.stripAnsi), params.delimiter) |
| 5650 |
trans := Transform(tokens, ranges) |
| 5651 |
str := JoinTokens(trans) |
| 5652 |
|
| 5653 |
// trim the last delimiter |
| 5654 |
if params.delimiter.str != nil { |
| 5655 |
str = strings.TrimSuffix(str, *params.delimiter.str) |
| 5656 |
} else if params.delimiter.regex != nil { |
| 5657 |
delims := params.delimiter.regex.FindAllStringIndex(str, -1) |
| 5658 |
// make sure the delimiter is at the very end of the string |
| 5659 |
if len(delims) > 0 && delims[len(delims)-1][1] == len(str) { |
| 5660 |
str = str[:delims[len(delims)-1][0]] |
| 5661 |
} |
| 5662 |
} |
| 5663 |
|
| 5664 |
if !flags.preserveSpace { |
| 5665 |
str = strings.TrimSpace(str) |
| 5666 |
} |
| 5667 |
if !flags.file && !flags.raw { |
| 5668 |
str = params.executor.QuoteEntry(str) |
| 5669 |
} |
| 5670 |
return str |
| 5671 |
} |
| 5672 |
} |
| 5673 |
|
| 5674 |
// apply 'replace' function over proper set of items and return result |
| 5675 |
|
| 5676 |
items := current |
| 5677 |
if flags.asterisk { |
| 5678 |
items = matched |
| 5679 |
} else if flags.plus || params.forcePlus { |
| 5680 |
items = selected |
| 5681 |
} |
| 5682 |
replacements := make([]string, len(items)) |
| 5683 |
|
| 5684 |
for idx, item := range items { |
| 5685 |
replacements[idx] = replace(item) |
| 5686 |
} |
| 5687 |
|
| 5688 |
if flags.file { |
| 5689 |
file := WriteTemporaryFile(replacements, params.printsep) |
| 5690 |
tempFiles = append(tempFiles, file) |
| 5691 |
return file |
| 5692 |
} |
| 5693 |
return strings.Join(replacements, " ") |
| 5694 |
}) |
| 5695 |
|
| 5696 |
return replaced, tempFiles |
| 5697 |
} |
| 5698 |
|
| 5699 |
func (t *Terminal) fullRedraw() { |
| 5700 |
t.tui.Clear() |
| 5701 |
t.tui.Refresh() |
| 5702 |
t.printAll() |
| 5703 |
} |
| 5704 |
|
| 5705 |
func (t *Terminal) captureLine(template string) string { |
| 5706 |
return t.executeCommand(template, false, true, true, true, "") |
| 5707 |
} |
| 5708 |
|
| 5709 |
func (t *Terminal) captureLines(template string) string { |
| 5710 |
return t.executeCommand(template, false, true, true, false, "") |
| 5711 |
} |
| 5712 |
|
| 5713 |
func (t *Terminal) captureAsync(a action, firstLineOnly bool, callback func(string)) { |
| 5714 |
_, list := t.buildPlusList(a.a, false) |
| 5715 |
command, tempFiles := t.replacePlaceholder(a.a, false, string(t.input), list) |
| 5716 |
version := t.bgVersion |
| 5717 |
cmd := t.executor.ExecCommand(command, true) |
| 5718 |
cmd.Env = t.environ() |
| 5719 |
item := func(proceed bool) { |
| 5720 |
if proceed { |
| 5721 |
out, _ := cmd.StdoutPipe() |
| 5722 |
reader := bufio.NewReader(out) |
| 5723 |
var output string |
| 5724 |
if err := cmd.Start(); err == nil { |
| 5725 |
runningCmd := runningCmd{cmd, tempFiles} |
| 5726 |
t.runningCmds.Add(&runningCmd) |
| 5727 |
if firstLineOnly { |
| 5728 |
output, _ = reader.ReadString('\n') |
| 5729 |
output = strings.TrimRight(output, "\r\n") |
| 5730 |
} else { |
| 5731 |
bytes, _ := io.ReadAll(reader) |
| 5732 |
output = string(bytes) |
| 5733 |
} |
| 5734 |
cmd.Wait() |
| 5735 |
t.runningCmds.Remove(&runningCmd) |
| 5736 |
} |
| 5737 |
t.callbackChan <- versionedCallback{version, func() { callback(output) }} |
| 5738 |
} |
| 5739 |
removeFiles(tempFiles) |
| 5740 |
|
| 5741 |
} |
| 5742 |
queue, prs := t.bgQueue[a] |
| 5743 |
if !prs { |
| 5744 |
queue = []func(bool){} |
| 5745 |
} |
| 5746 |
queue = append(queue, item) |
| 5747 |
t.bgQueue[a] = queue |
| 5748 |
} |
| 5749 |
|
| 5750 |
func (t *Terminal) dispatchAsync() { |
| 5751 |
Loop: |
| 5752 |
for a, queue := range t.bgQueue { |
| 5753 |
delete(t.bgQueue, a) |
| 5754 |
if len(queue) == 0 { |
| 5755 |
continue |
| 5756 |
} |
| 5757 |
|
| 5758 |
semaphore, prs := t.bgSemaphores[a] |
| 5759 |
if !prs { |
| 5760 |
semaphore = make(chan struct{}, maxBgProcessesPerAction) |
| 5761 |
t.bgSemaphores[a] = semaphore |
| 5762 |
} |
| 5763 |
for _, item := range queue { |
| 5764 |
select { |
| 5765 |
// Acquire local semaphore |
| 5766 |
case semaphore <- struct{}{}: |
| 5767 |
default: |
| 5768 |
// Failed to acquire local semaphore, putting only the last one back to the queue |
| 5769 |
for _, item := range queue[:len(queue)-1] { |
| 5770 |
item(false) |
| 5771 |
} |
| 5772 |
t.bgQueue[a] = queue[len(queue)-1:] |
| 5773 |
continue Loop |
| 5774 |
} |
| 5775 |
todo := item |
| 5776 |
go func() { |
| 5777 |
// Acquire global semaphore |
| 5778 |
t.bgSemaphore <- struct{}{} |
| 5779 |
|
| 5780 |
todo(true) |
| 5781 |
// Release local semaphore |
| 5782 |
<-semaphore |
| 5783 |
// Release global semaphore |
| 5784 |
<-t.bgSemaphore |
| 5785 |
}() |
| 5786 |
} |
| 5787 |
} |
| 5788 |
} |
| 5789 |
|
| 5790 |
func (t *Terminal) executeCommand(template string, forcePlus bool, background bool, capture bool, firstLineOnly bool, info string) string { |
| 5791 |
line := "" |
| 5792 |
valid, list := t.buildPlusList(template, forcePlus) |
| 5793 |
// 'capture' is used for transform-* and we don't want to |
| 5794 |
// return an empty string in those cases |
| 5795 |
if !valid && !capture { |
| 5796 |
return line |
| 5797 |
} |
| 5798 |
command, tempFiles := t.replacePlaceholder(template, forcePlus, string(t.input), list) |
| 5799 |
cmd := t.executor.ExecCommand(command, false) |
| 5800 |
cmd.Env = t.environ() |
| 5801 |
if len(info) > 0 { |
| 5802 |
cmd.Env = append(cmd.Env, "FZF_INFO="+info) |
| 5803 |
} |
| 5804 |
t.executing.Set(true) |
| 5805 |
if !background { |
| 5806 |
// Open a separate handle for tty input |
| 5807 |
if in, _ := tui.TtyIn(t.ttyDefault); in != nil { |
| 5808 |
cmd.Stdin = in |
| 5809 |
if in != os.Stdin { |
| 5810 |
defer in.Close() |
| 5811 |
} |
| 5812 |
} |
| 5813 |
|
| 5814 |
cmd.Stdout = os.Stdout |
| 5815 |
if !util.IsTty(os.Stdout) { |
| 5816 |
if out, _ := tui.TtyOut(t.ttyDefault); out != nil { |
| 5817 |
cmd.Stdout = out |
| 5818 |
defer out.Close() |
| 5819 |
} |
| 5820 |
} |
| 5821 |
|
| 5822 |
cmd.Stderr = os.Stderr |
| 5823 |
if !util.IsTty(os.Stderr) { |
| 5824 |
if out, _ := tui.TtyOut(t.ttyDefault); out != nil { |
| 5825 |
cmd.Stderr = out |
| 5826 |
defer out.Close() |
| 5827 |
} |
| 5828 |
} |
| 5829 |
|
| 5830 |
t.mutex.Unlock() |
| 5831 |
if len(info) == 0 { |
| 5832 |
t.uiMutex.Lock() |
| 5833 |
} |
| 5834 |
t.tui.Pause(true) |
| 5835 |
cmd.Run() |
| 5836 |
t.tui.Resume(true, false) |
| 5837 |
t.mutex.Lock() |
| 5838 |
// NOTE: Using t.reqBox.Set(reqFullRedraw...) instead can cause a deadlock |
| 5839 |
t.fullRedraw() |
| 5840 |
t.flush() |
| 5841 |
} else { |
| 5842 |
t.mutex.Unlock() |
| 5843 |
if len(info) == 0 { |
| 5844 |
t.uiMutex.Lock() |
| 5845 |
} |
| 5846 |
paused := atomic.Int32{} |
| 5847 |
ctx, cancel := context.WithCancel(context.Background()) |
| 5848 |
go func() { |
| 5849 |
select { |
| 5850 |
case <-ctx.Done(): |
| 5851 |
return |
| 5852 |
case <-time.After(blockDuration): |
| 5853 |
if paused.CompareAndSwap(0, 1) { |
| 5854 |
t.tui.Pause(false) |
| 5855 |
} |
| 5856 |
} |
| 5857 |
}() |
| 5858 |
if capture { |
| 5859 |
out, _ := cmd.StdoutPipe() |
| 5860 |
reader := bufio.NewReader(out) |
| 5861 |
cmd.Start() |
| 5862 |
if firstLineOnly { |
| 5863 |
line, _ = reader.ReadString('\n') |
| 5864 |
line = strings.TrimRight(line, "\r\n") |
| 5865 |
} else { |
| 5866 |
bytes, _ := io.ReadAll(reader) |
| 5867 |
line = string(bytes) |
| 5868 |
} |
| 5869 |
cmd.Wait() |
| 5870 |
} else { |
| 5871 |
cmd.Run() |
| 5872 |
} |
| 5873 |
cancel() |
| 5874 |
if paused.CompareAndSwap(1, 2) { |
| 5875 |
t.tui.Resume(false, false) |
| 5876 |
} |
| 5877 |
t.mutex.Lock() |
| 5878 |
|
| 5879 |
// Redraw prompt in case the user has typed something after blockDuration |
| 5880 |
if paused.Load() > 0 { |
| 5881 |
// NOTE: Using t.reqBox.Set(reqXXX...) instead can cause a deadlock |
| 5882 |
t.printPrompt() |
| 5883 |
if t.infoStyle == infoInline || t.infoStyle == infoInlineRight { |
| 5884 |
t.printInfo() |
| 5885 |
} |
| 5886 |
} |
| 5887 |
} |
| 5888 |
if len(info) == 0 { |
| 5889 |
t.uiMutex.Unlock() |
| 5890 |
} |
| 5891 |
t.executing.Set(false) |
| 5892 |
removeFiles(tempFiles) |
| 5893 |
return line |
| 5894 |
} |
| 5895 |
|
| 5896 |
func (t *Terminal) hasPreviewer() bool { |
| 5897 |
return t.previewBox != nil |
| 5898 |
} |
| 5899 |
|
| 5900 |
func (t *Terminal) needPreviewWindow() bool { |
| 5901 |
return t.hasPreviewer() && len(t.previewOpts.command) > 0 && t.activePreviewOpts.Visible() |
| 5902 |
} |
| 5903 |
|
| 5904 |
// Check if previewer is currently in action (invisible previewer with size 0 or visible previewer) |
| 5905 |
func (t *Terminal) canPreview() bool { |
| 5906 |
return t.hasPreviewer() && (!t.activePreviewOpts.Visible() && !t.activePreviewOpts.hidden || t.hasPreviewWindow()) |
| 5907 |
} |
| 5908 |
|
| 5909 |
func (t *Terminal) hasPreviewWindow() bool { |
| 5910 |
return t.pwindow != nil |
| 5911 |
} |
| 5912 |
|
| 5913 |
func (t *Terminal) hasPreviewWindowOnRight() bool { |
| 5914 |
return t.hasPreviewWindow() && t.activePreviewOpts.position == posRight |
| 5915 |
} |
| 5916 |
|
| 5917 |
func (t *Terminal) currentItem() *Item { |
| 5918 |
cnt := t.merger.Length() |
| 5919 |
if t.cy >= 0 && cnt > 0 && cnt > t.cy { |
| 5920 |
return t.merger.Get(t.cy).item |
| 5921 |
} |
| 5922 |
return nil |
| 5923 |
} |
| 5924 |
|
| 5925 |
func (t *Terminal) isCurrentItemMatch() bool { |
| 5926 |
cnt := t.merger.Length() |
| 5927 |
if t.cy >= 0 && cnt > 0 && cnt > t.cy { |
| 5928 |
if !t.raw { |
| 5929 |
return true |
| 5930 |
} |
| 5931 |
item := t.merger.Get(t.cy).item |
| 5932 |
return t.isItemMatch(item) |
| 5933 |
} |
| 5934 |
return false |
| 5935 |
} |
| 5936 |
|
| 5937 |
func (t *Terminal) isItemMatch(item *Item) bool { |
| 5938 |
_, matched := t.matchMap[item.Index()] |
| 5939 |
return matched |
| 5940 |
} |
| 5941 |
|
| 5942 |
func (t *Terminal) filterSelected() { |
| 5943 |
filtered := make(map[int32]selectedItem) |
| 5944 |
for k, v := range t.selected { |
| 5945 |
if t.isItemMatch(v.item) { |
| 5946 |
filtered[k] = v |
| 5947 |
} |
| 5948 |
} |
| 5949 |
t.selected = filtered |
| 5950 |
} |
| 5951 |
|
| 5952 |
func (t *Terminal) buildPlusList(template string, forcePlus bool) (bool, [3][]*Item) { |
| 5953 |
current := t.currentItem() |
| 5954 |
slot, plus, asterisk, forceUpdate := hasPreviewFlags(template) |
| 5955 |
if !(!slot || forceUpdate || asterisk || (forcePlus || plus) && len(t.selected) > 0) { |
| 5956 |
if current == nil { |
| 5957 |
// Invalid |
| 5958 |
return false, [3][]*Item{nil, nil, nil} |
| 5959 |
} |
| 5960 |
return true, [3][]*Item{{current}, {current}, nil} |
| 5961 |
} |
| 5962 |
|
| 5963 |
// We would still want to update preview window even if there is no match if |
| 5964 |
// 1. the command template contains {q} |
| 5965 |
// 2. or it contains {+} and we have more than one item already selected. |
| 5966 |
// To do so, we pass an empty Item instead of nil to trigger an update. |
| 5967 |
if current == nil { |
| 5968 |
current = &minItem |
| 5969 |
} |
| 5970 |
|
| 5971 |
var all []*Item |
| 5972 |
if asterisk { |
| 5973 |
cnt := t.merger.Length() |
| 5974 |
all = make([]*Item, cnt) |
| 5975 |
for i := range cnt { |
| 5976 |
all[i] = t.merger.Get(i).item |
| 5977 |
} |
| 5978 |
} |
| 5979 |
|
| 5980 |
var sels []*Item |
| 5981 |
if len(t.selected) == 0 { |
| 5982 |
sels = []*Item{current} |
| 5983 |
} else if len(t.selected) > 0 { |
| 5984 |
sels = make([]*Item, len(t.selected)) |
| 5985 |
for i, sel := range t.sortSelected() { |
| 5986 |
sels[i] = sel.item |
| 5987 |
} |
| 5988 |
} |
| 5989 |
return true, [3][]*Item{{current}, sels, all} |
| 5990 |
} |
| 5991 |
|
| 5992 |
func (t *Terminal) selectItem(item *Item) bool { |
| 5993 |
if len(t.selected) >= t.multi { |
| 5994 |
return false |
| 5995 |
} |
| 5996 |
if _, found := t.selected[item.Index()]; found { |
| 5997 |
return true |
| 5998 |
} |
| 5999 |
|
| 6000 |
t.selected[item.Index()] = selectedItem{time.Now(), item} |
| 6001 |
t.version++ |
| 6002 |
|
| 6003 |
return true |
| 6004 |
} |
| 6005 |
|
| 6006 |
func (t *Terminal) selectItemChanged(item *Item) bool { |
| 6007 |
if _, found := t.selected[item.Index()]; found { |
| 6008 |
return false |
| 6009 |
} |
| 6010 |
return t.selectItem(item) |
| 6011 |
} |
| 6012 |
|
| 6013 |
func (t *Terminal) deselectItem(item *Item) { |
| 6014 |
delete(t.selected, item.Index()) |
| 6015 |
t.version++ |
| 6016 |
} |
| 6017 |
|
| 6018 |
func (t *Terminal) deselectItemChanged(item *Item) bool { |
| 6019 |
if _, found := t.selected[item.Index()]; found { |
| 6020 |
t.deselectItem(item) |
| 6021 |
return true |
| 6022 |
} |
| 6023 |
return false |
| 6024 |
} |
| 6025 |
|
| 6026 |
func (t *Terminal) toggleItem(item *Item) bool { |
| 6027 |
if _, found := t.selected[item.Index()]; !found { |
| 6028 |
return t.selectItem(item) |
| 6029 |
} |
| 6030 |
t.deselectItem(item) |
| 6031 |
return true |
| 6032 |
} |
| 6033 |
|
| 6034 |
func (t *Terminal) killPreview() { |
| 6035 |
select { |
| 6036 |
case t.killChan <- true: |
| 6037 |
<-t.killedChan |
| 6038 |
default: |
| 6039 |
} |
| 6040 |
} |
| 6041 |
|
| 6042 |
func (t *Terminal) cancelPreview() { |
| 6043 |
select { |
| 6044 |
case t.killChan <- false: |
| 6045 |
default: |
| 6046 |
} |
| 6047 |
} |
| 6048 |
|
| 6049 |
func (t *Terminal) pwindowSize() tui.TermSize { |
| 6050 |
if t.pwindow == nil { |
| 6051 |
return tui.TermSize{} |
| 6052 |
} |
| 6053 |
size := tui.TermSize{Lines: t.pwindow.Height(), Columns: t.pwindow.Width()} |
| 6054 |
|
| 6055 |
if t.termSize.PxWidth > 0 { |
| 6056 |
size.PxWidth = size.Columns * t.termSize.PxWidth / t.termSize.Columns |
| 6057 |
size.PxHeight = size.Lines * t.termSize.PxHeight / t.termSize.Lines |
| 6058 |
} |
| 6059 |
return size |
| 6060 |
} |
| 6061 |
|
| 6062 |
func (t *Terminal) currentIndex() int32 { |
| 6063 |
if currentItem := t.currentItem(); currentItem != nil { |
| 6064 |
return currentItem.Index() |
| 6065 |
} |
| 6066 |
return minItem.Index() |
| 6067 |
} |
| 6068 |
|
| 6069 |
func (t *Terminal) trackKeyFor(item *Item, nth []Range) string { |
| 6070 |
tokens := Tokenize(item.AsString(t.ansi), t.delimiter) |
| 6071 |
return StripLastDelimiter(JoinTokens(Transform(tokens, nth)), t.delimiter) |
| 6072 |
} |
| 6073 |
|
| 6074 |
func (t *Terminal) unblockTrack() { |
| 6075 |
if t.trackBlocked { |
| 6076 |
t.trackBlocked = false |
| 6077 |
t.trackKey = "" |
| 6078 |
t.trackKeyCache = nil |
| 6079 |
// Keep the cursor hidden if the wait feedback is still showing it |
| 6080 |
if !t.inputless && !t.waitFeedback() { |
| 6081 |
t.tui.ShowCursor() |
| 6082 |
} |
| 6083 |
} |
| 6084 |
} |
| 6085 |
|
| 6086 |
// The wait state machine. Invariant: arming captures every action after |
| 6087 |
// 'wait' at any nesting level into wait.pending; while blocked, actions are |
| 6088 |
// dropped unless they are results of work started before the block |
| 6089 |
// (bg-transform callbacks, bracketed paste bookkeeping); abort/cancel |
| 6090 |
// discards everything. |
| 6091 |
|
| 6092 |
// blockWait blocks action execution and defers the given actions until the |
| 6093 |
// current search completes (see UpdateList) |
| 6094 |
func (t *Terminal) blockWait(pending []*action) { |
| 6095 |
t.wait.blocked = true |
| 6096 |
t.wait.blockedAt = time.Now() |
| 6097 |
// Clone so that later joins don't append into the backing array of the |
| 6098 |
// bound action list |
| 6099 |
t.wait.pending = slices.Clone(pending) |
| 6100 |
// Show the waiting feedback only if the search takes long enough, |
| 6101 |
// so that quick searches don't cause flickering |
| 6102 |
go func() { |
| 6103 |
timer := time.NewTimer(progressMinDuration) |
| 6104 |
<-timer.C |
| 6105 |
t.mutex.Lock() |
| 6106 |
blocked := t.wait.blocked |
| 6107 |
t.mutex.Unlock() |
| 6108 |
if blocked { |
| 6109 |
t.reqBox.Set(reqPrompt, nil) |
| 6110 |
t.reqBox.Set(reqInfo, nil) |
| 6111 |
} |
| 6112 |
}() |
| 6113 |
} |
| 6114 |
|
| 6115 |
// unblockWait lifts the block, leaving the pending actions to the caller: |
| 6116 |
// UpdateList keeps them for the main loop to replay, cancelWait discards them |
| 6117 |
func (t *Terminal) unblockWait() { |
| 6118 |
t.wait.blocked = false |
| 6119 |
// Restore the cursor unless it's still hidden for another reason |
| 6120 |
if !t.inputless && !t.trackBlocked { |
| 6121 |
t.tui.ShowCursor() |
| 6122 |
} |
| 6123 |
} |
| 6124 |
|
| 6125 |
// cancelWait unblocks and discards the pending actions (user abort) |
| 6126 |
func (t *Terminal) cancelWait() { |
| 6127 |
t.unblockWait() |
| 6128 |
t.wait.pending = nil |
| 6129 |
} |
| 6130 |
|
| 6131 |
// Debounce visual feedback so quick searches don't cause flashing |
| 6132 |
func (t *Terminal) waitFeedback() bool { |
| 6133 |
return t.wait.blocked && time.Since(t.wait.blockedAt) > progressMinDuration |
| 6134 |
} |
| 6135 |
|
| 6136 |
func (t *Terminal) addClickHeaderWord(env []string) []string { |
| 6137 |
/* |
| 6138 |
* echo $'HL1\nHL2' | fzf --header-lines 3 --header $'H1\nH2' --header-lines-border --bind 'click-header:preview:env | grep FZF_CLICK' |
| 6139 |
* |
| 6140 |
* REVERSE DEFAULT REVERSE-LIST |
| 6141 |
* H1 1 1 HL1 1 |
| 6142 |
* H2 2 HL2 2 HL2 2 |
| 6143 |
* ------- HL1 3 3 |
| 6144 |
* HL1 3 ------- ------- |
| 6145 |
* HL2 4 H1 4 H1 4 |
| 6146 |
* 5 H2 5 H2 5 |
| 6147 |
*/ |
| 6148 |
clickHeaderLine := t.clickHeaderLine - 1 |
| 6149 |
if clickHeaderLine < 0 { |
| 6150 |
// Never clicked on the header |
| 6151 |
return env |
| 6152 |
} |
| 6153 |
|
| 6154 |
nthBase := 0 |
| 6155 |
// Convert header items to strings for click handling |
| 6156 |
headerStrs := make([]string, len(t.header)) |
| 6157 |
for i, item := range t.header { |
| 6158 |
headerStrs[i] = item.text.ToString() |
| 6159 |
} |
| 6160 |
headers := [2][]string{headerStrs, t.header0} |
| 6161 |
if t.layout == layoutReverse { |
| 6162 |
headers[0], headers[1] = headers[1], headers[0] |
| 6163 |
} |
| 6164 |
var trimmedLine string |
| 6165 |
var words []Token |
| 6166 |
var lineNum int |
| 6167 |
for lineNum = 0; lineNum <= clickHeaderLine; lineNum++ { |
| 6168 |
currentLine := lineNum == clickHeaderLine |
| 6169 |
var line string |
| 6170 |
if lineNum < len(headers[0]) { |
| 6171 |
index := lineNum |
| 6172 |
if t.layout == layoutDefault { |
| 6173 |
index = len(headers[0]) - index - 1 |
| 6174 |
} |
| 6175 |
line = headers[0][index] |
| 6176 |
} else if lineNum-len(headers[0]) < len(headers[1]) { |
| 6177 |
line = headers[1][lineNum-len(headers[0])] |
| 6178 |
} |
| 6179 |
if currentLine && len(line) == 0 { |
| 6180 |
return env |
| 6181 |
} |
| 6182 |
|
| 6183 |
// NOTE: We can't expand tabs here because the delimiter can contain tabs. |
| 6184 |
trimmedLine, _, _ = extractColor(line, nil, nil) |
| 6185 |
words = Tokenize(trimmedLine, t.delimiter) |
| 6186 |
if currentLine { |
| 6187 |
break |
| 6188 |
} else { |
| 6189 |
// TODO: Counting can be incorrect when the delimiter contains new line |
| 6190 |
// characters, and there are empty lines in the header. |
| 6191 |
nthBase += len(words) |
| 6192 |
} |
| 6193 |
} |
| 6194 |
|
| 6195 |
colNum := t.clickHeaderColumn - 1 |
| 6196 |
prefixWidth, prefixLength := 0, 0 |
| 6197 |
for idx, token := range words { |
| 6198 |
prefixWidth += t.displayWidthWithPrefix(trimmedLine[prefixLength:token.prefixLength], prefixWidth) |
| 6199 |
prefixLength = int(token.prefixLength) |
| 6200 |
|
| 6201 |
word, _ := t.processTabs(token.text.ToRunes(), prefixWidth) |
| 6202 |
trimmed := strings.TrimRightFunc(word, unicode.IsSpace) |
| 6203 |
trimWidth := t.displayWidthWithPrefix(trimmed, prefixWidth) |
| 6204 |
|
| 6205 |
// Find the position of the first non-space character in the word |
| 6206 |
minPos := strings.IndexFunc(trimmed, func(r rune) bool { |
| 6207 |
return !unicode.IsSpace(r) |
| 6208 |
}) |
| 6209 |
if colNum >= minPos && colNum >= prefixWidth && colNum < prefixWidth+trimWidth { |
| 6210 |
env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_WORD=%s", trimmed)) |
| 6211 |
nth := fmt.Sprintf("FZF_CLICK_HEADER_NTH=%d", nthBase+idx+1) |
| 6212 |
if lineNum == len(t.header)+len(t.header0)-1 && idx == len(words)-1 { |
| 6213 |
nth += ".." |
| 6214 |
} |
| 6215 |
env = append(env, nth) |
| 6216 |
return env |
| 6217 |
} |
| 6218 |
} |
| 6219 |
return env |
| 6220 |
} |
| 6221 |
|
| 6222 |
func (t *Terminal) addClickFooterWord(env []string) []string { |
| 6223 |
clickFooterLine := t.clickFooterLine - 1 |
| 6224 |
if clickFooterLine < 0 || clickFooterLine >= len(t.footer) { |
| 6225 |
// Never clicked on the footer |
| 6226 |
return env |
| 6227 |
} |
| 6228 |
|
| 6229 |
// NOTE: Unlike in click-header, we don't use --delimiter here, since we're |
| 6230 |
// only interested in the word, not nth. Does this make sense? |
| 6231 |
trimmed, _, _ := extractColor(t.footer[clickFooterLine], nil, nil) |
| 6232 |
trimmed, _ = t.processTabsStr(trimmed, 0) |
| 6233 |
words := Tokenize(trimmed, Delimiter{}) |
| 6234 |
colNum := t.clickFooterColumn - 1 |
| 6235 |
for _, token := range words { |
| 6236 |
prefixWidth := int(token.prefixLength) |
| 6237 |
word := token.text.ToString() |
| 6238 |
trimmed := strings.TrimRightFunc(word, unicode.IsSpace) |
| 6239 |
trimWidth := t.displayWidthWithPrefix(trimmed, prefixWidth) |
| 6240 |
|
| 6241 |
// Find the position of the first non-space character in the word |
| 6242 |
minPos := strings.IndexFunc(trimmed, func(r rune) bool { |
| 6243 |
return !unicode.IsSpace(r) |
| 6244 |
}) |
| 6245 |
if colNum >= minPos && colNum >= prefixWidth && colNum < prefixWidth+trimWidth { |
| 6246 |
env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_WORD=%s", trimmed)) |
| 6247 |
return env |
| 6248 |
} |
| 6249 |
} |
| 6250 |
return env |
| 6251 |
} |
| 6252 |
|
| 6253 |
// startTimers spawns a goroutine per every() bind event. Forwarding ticks |
| 6254 |
// onto the unbuffered timerChan lets the ticker drop overlapping ticks |
| 6255 |
// while the main loop is busy. |
| 6256 |
func (t *Terminal) startTimers(ctx context.Context) { |
| 6257 |
for evt := range t.keymap { |
| 6258 |
switch evt.Type { |
| 6259 |
case tui.Every: |
| 6260 |
d := time.Duration(evt.Char) * time.Millisecond |
| 6261 |
evt := evt |
| 6262 |
go func() { |
| 6263 |
ticker := time.NewTicker(d) |
| 6264 |
defer ticker.Stop() |
| 6265 |
for { |
| 6266 |
select { |
| 6267 |
case <-ctx.Done(): |
| 6268 |
return |
| 6269 |
case <-ticker.C: |
| 6270 |
select { |
| 6271 |
case <-ctx.Done(): |
| 6272 |
return |
| 6273 |
case t.timerChan <- evt: |
| 6274 |
} |
| 6275 |
} |
| 6276 |
} |
| 6277 |
}() |
| 6278 |
} |
| 6279 |
} |
| 6280 |
} |
| 6281 |
|
| 6282 |
// Loop is called to start Terminal I/O |
| 6283 |
func (t *Terminal) Loop() error { |
| 6284 |
// prof := profile.Start(profile.ProfilePath("/tmp/")) |
| 6285 |
fitpad := <-t.startChan |
| 6286 |
fit := fitpad.fit |
| 6287 |
if fit >= 0 { |
| 6288 |
pad := fitpad.pad |
| 6289 |
t.tui.Resize(func(termHeight int) int { |
| 6290 |
contentHeight := fit + t.extraLines() |
| 6291 |
if t.needPreviewWindow() { |
| 6292 |
if t.activePreviewOpts.aboveOrBelow() { |
| 6293 |
if t.activePreviewOpts.size.percent { |
| 6294 |
newContentHeight := int(float64(contentHeight) * 100. / (100. - t.activePreviewOpts.size.size)) |
| 6295 |
contentHeight = max(contentHeight+1+borderLines(t.activePreviewOpts.Border(t.layout)), newContentHeight) |
| 6296 |
} else { |
| 6297 |
contentHeight += int(t.activePreviewOpts.size.size) + borderLines(t.activePreviewOpts.Border(t.layout)) |
| 6298 |
} |
| 6299 |
} else { |
| 6300 |
// Minimum height if preview window can appear |
| 6301 |
contentHeight = max(contentHeight, 1+borderLines(t.activePreviewOpts.Border(t.layout))) |
| 6302 |
} |
| 6303 |
} |
| 6304 |
return min(termHeight, contentHeight+pad) |
| 6305 |
}) |
| 6306 |
} |
| 6307 |
|
| 6308 |
// Context |
| 6309 |
ctx, cancel := context.WithCancel(context.Background()) |
| 6310 |
|
| 6311 |
{ // Late initialization |
| 6312 |
intChan := make(chan os.Signal, 1) |
| 6313 |
signal.Notify(intChan, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) |
| 6314 |
go func() { |
| 6315 |
for { |
| 6316 |
select { |
| 6317 |
case <-ctx.Done(): |
| 6318 |
signal.Stop(intChan) |
| 6319 |
return |
| 6320 |
case s := <-intChan: |
| 6321 |
// Don't quit by SIGINT while executing because it should be for the executing command and not for fzf itself |
| 6322 |
if !(s == os.Interrupt && t.executing.Get()) { |
| 6323 |
t.reqBox.Set(reqQuit, nil) |
| 6324 |
} |
| 6325 |
} |
| 6326 |
} |
| 6327 |
}() |
| 6328 |
|
| 6329 |
if !t.tui.ShouldEmitResizeEvent() { |
| 6330 |
resizeChan := make(chan os.Signal, 1) |
| 6331 |
notifyOnResize(ctx, resizeChan) // Non-portable |
| 6332 |
go func() { |
| 6333 |
for { |
| 6334 |
select { |
| 6335 |
case <-ctx.Done(): |
| 6336 |
return |
| 6337 |
case <-resizeChan: |
| 6338 |
t.reqBox.Set(reqResize, nil) |
| 6339 |
} |
| 6340 |
} |
| 6341 |
}() |
| 6342 |
} |
| 6343 |
|
| 6344 |
t.mutex.Lock() |
| 6345 |
if err := t.initFunc(); err != nil { |
| 6346 |
t.mutex.Unlock() |
| 6347 |
cancel() |
| 6348 |
t.eventBox.Set(EvtQuit, quitSignal{ExitError, err}) |
| 6349 |
return err |
| 6350 |
} |
| 6351 |
t.termSize = t.tui.Size() |
| 6352 |
t.resizeWindows(false, false) |
| 6353 |
t.window.Erase() |
| 6354 |
t.mutex.Unlock() |
| 6355 |
|
| 6356 |
t.reqBox.Set(reqPrompt, nil) |
| 6357 |
t.reqBox.Set(reqInfo, nil) |
| 6358 |
t.reqBox.Set(reqHeader, nil) |
| 6359 |
t.reqBox.Set(reqFooter, nil) |
| 6360 |
if t.initDelay > 0 { |
| 6361 |
go func() { |
| 6362 |
timer := time.NewTimer(t.initDelay) |
| 6363 |
<-timer.C |
| 6364 |
t.reqBox.Set(reqActivate, nil) |
| 6365 |
}() |
| 6366 |
} |
| 6367 |
|
| 6368 |
// Keep the spinner spinning |
| 6369 |
go func() { |
| 6370 |
for t.running.Get() { |
| 6371 |
t.mutex.Lock() |
| 6372 |
reading := t.reading |
| 6373 |
t.mutex.Unlock() |
| 6374 |
time.Sleep(spinnerDuration) |
| 6375 |
if reading { |
| 6376 |
t.reqBox.Set(reqInfo, nil) |
| 6377 |
} |
| 6378 |
} |
| 6379 |
}() |
| 6380 |
} |
| 6381 |
|
| 6382 |
if t.hasPreviewer() { |
| 6383 |
go func() { |
| 6384 |
var version int64 |
| 6385 |
stop := false |
| 6386 |
t.previewBox.WaitFor(reqPreviewReady) |
| 6387 |
for { |
| 6388 |
requested := false |
| 6389 |
var items [3][]*Item |
| 6390 |
var commandTemplate string |
| 6391 |
var env []string |
| 6392 |
var query string |
| 6393 |
initialOffset := 0 |
| 6394 |
t.previewBox.Wait(func(events *util.Events) { |
| 6395 |
for req, value := range *events { |
| 6396 |
switch req { |
| 6397 |
case reqQuit: |
| 6398 |
stop = true |
| 6399 |
return |
| 6400 |
case reqPreviewEnqueue: |
| 6401 |
request := value.(previewRequest) |
| 6402 |
commandTemplate = request.template |
| 6403 |
initialOffset = request.scrollOffset |
| 6404 |
items = request.list |
| 6405 |
env = request.env |
| 6406 |
query = request.query |
| 6407 |
requested = true |
| 6408 |
} |
| 6409 |
} |
| 6410 |
events.Clear() |
| 6411 |
}) |
| 6412 |
if stop { |
| 6413 |
break |
| 6414 |
} |
| 6415 |
if !requested { |
| 6416 |
continue |
| 6417 |
} |
| 6418 |
version++ |
| 6419 |
// We don't display preview window if no match |
| 6420 |
if items[0] != nil { |
| 6421 |
command, tempFiles := t.replacePlaceholder(commandTemplate, false, query, items) |
| 6422 |
cmd := t.executor.ExecCommand(command, true) |
| 6423 |
cmd.Env = env |
| 6424 |
|
| 6425 |
out, _ := cmd.StdoutPipe() |
| 6426 |
cmd.Stderr = cmd.Stdout |
| 6427 |
reader := bufio.NewReader(out) |
| 6428 |
eofChan := make(chan bool) |
| 6429 |
finishChan := make(chan bool, 1) |
| 6430 |
err := cmd.Start() |
| 6431 |
if err == nil { |
| 6432 |
reapChan := make(chan bool) |
| 6433 |
lineChan := make(chan eachLine) |
| 6434 |
// Goroutine 1 reads process output |
| 6435 |
go func() { |
| 6436 |
for { |
| 6437 |
line, err := reader.ReadString('\n') |
| 6438 |
lineChan <- eachLine{line, err} |
| 6439 |
if err != nil { |
| 6440 |
break |
| 6441 |
} |
| 6442 |
} |
| 6443 |
eofChan <- true |
| 6444 |
}() |
| 6445 |
|
| 6446 |
// Goroutine 2 periodically requests rendering |
| 6447 |
rendered := util.NewAtomicBool(false) |
| 6448 |
go func(version int64) { |
| 6449 |
lines := []string{} |
| 6450 |
spinner := makeSpinner(t.unicode) |
| 6451 |
spinnerIndex := -1 // Delay initial rendering by an extra tick |
| 6452 |
ticker := time.NewTicker(previewChunkDelay) |
| 6453 |
offset := initialOffset |
| 6454 |
Loop: |
| 6455 |
for { |
| 6456 |
select { |
| 6457 |
case <-ticker.C: |
| 6458 |
if len(lines) > 0 && len(lines) >= initialOffset { |
| 6459 |
if spinnerIndex >= 0 { |
| 6460 |
spin := spinner[spinnerIndex%len(spinner)] |
| 6461 |
t.reqBox.Set(reqPreviewDisplay, previewResult{version, lines, offset, spin}) |
| 6462 |
rendered.Set(true) |
| 6463 |
offset = -1 |
| 6464 |
} |
| 6465 |
spinnerIndex++ |
| 6466 |
} |
| 6467 |
case eachLine := <-lineChan: |
| 6468 |
line := eachLine.line |
| 6469 |
err := eachLine.err |
| 6470 |
if len(line) > 0 { |
| 6471 |
clearIndex := strings.Index(line, clearCode) |
| 6472 |
if clearIndex >= 0 { |
| 6473 |
lines = []string{} |
| 6474 |
line = line[clearIndex+len(clearCode):] |
| 6475 |
version-- |
| 6476 |
offset = 0 |
| 6477 |
} |
| 6478 |
if split := t.splitOnIND(line); split != nil { |
| 6479 |
lines = append(lines, split...) |
| 6480 |
} else { |
| 6481 |
lines = append(lines, line) |
| 6482 |
} |
| 6483 |
} |
| 6484 |
if err != nil { |
| 6485 |
t.reqBox.Set(reqPreviewDisplay, previewResult{version, lines, offset, ""}) |
| 6486 |
rendered.Set(true) |
| 6487 |
break Loop |
| 6488 |
} |
| 6489 |
} |
| 6490 |
} |
| 6491 |
ticker.Stop() |
| 6492 |
reapChan <- true |
| 6493 |
}(version) |
| 6494 |
|
| 6495 |
// Goroutine 3 is responsible for cancelling running preview command |
| 6496 |
go func(version int64) { |
| 6497 |
timer := time.NewTimer(previewDelayed) |
| 6498 |
Loop: |
| 6499 |
for { |
| 6500 |
select { |
| 6501 |
case <-ctx.Done(): |
| 6502 |
break Loop |
| 6503 |
case <-timer.C: |
| 6504 |
t.reqBox.Set(reqPreviewDelayed, version) |
| 6505 |
case immediately := <-t.killChan: |
| 6506 |
if immediately { |
| 6507 |
util.KillCommand(cmd) |
| 6508 |
t.killedChan <- true |
| 6509 |
} else { |
| 6510 |
// We can immediately kill a long-running preview program |
| 6511 |
// once we started rendering its partial output |
| 6512 |
delay := previewCancelWait |
| 6513 |
if rendered.Get() { |
| 6514 |
delay = 0 |
| 6515 |
} |
| 6516 |
timer := time.NewTimer(delay) |
| 6517 |
select { |
| 6518 |
case <-timer.C: |
| 6519 |
util.KillCommand(cmd) |
| 6520 |
case <-finishChan: |
| 6521 |
} |
| 6522 |
timer.Stop() |
| 6523 |
} |
| 6524 |
break Loop |
| 6525 |
case <-finishChan: |
| 6526 |
break Loop |
| 6527 |
} |
| 6528 |
} |
| 6529 |
timer.Stop() |
| 6530 |
reapChan <- true |
| 6531 |
}(version) |
| 6532 |
|
| 6533 |
<-eofChan // Goroutine 1 finished |
| 6534 |
cmd.Wait() // NOTE: We should not call Wait before EOF |
| 6535 |
finishChan <- true // Tell Goroutine 3 to stop |
| 6536 |
<-reapChan // Goroutine 2 and 3 finished |
| 6537 |
<-reapChan |
| 6538 |
removeFiles(tempFiles) |
| 6539 |
} else { |
| 6540 |
// Failed to start the command. Report the error immediately. |
| 6541 |
t.reqBox.Set(reqPreviewDisplay, previewResult{version, []string{err.Error()}, 0, ""}) |
| 6542 |
} |
| 6543 |
} else { |
| 6544 |
t.reqBox.Set(reqPreviewDisplay, previewResult{version, nil, 0, ""}) |
| 6545 |
} |
| 6546 |
} |
| 6547 |
}() |
| 6548 |
} |
| 6549 |
|
| 6550 |
refreshPreview := func(command string) { |
| 6551 |
if len(command) > 0 && t.canPreview() { |
| 6552 |
_, list := t.buildPlusList(command, false) |
| 6553 |
t.cancelPreview() |
| 6554 |
t.previewBox.Set(reqPreviewEnqueue, previewRequest{command, t.evaluateScrollOffset(), list, t.environForPreview(), string(t.input)}) |
| 6555 |
} |
| 6556 |
} |
| 6557 |
|
| 6558 |
go func() { // Render loop |
| 6559 |
var focusedIndex = minItem.Index() |
| 6560 |
var version int64 = -1 |
| 6561 |
running := true |
| 6562 |
code := ExitError |
| 6563 |
exit := func(getCode func() int) { |
| 6564 |
if t.hasPreviewer() { |
| 6565 |
t.previewBox.Set(reqQuit, nil) |
| 6566 |
} |
| 6567 |
if t.listener != nil { |
| 6568 |
t.listener.Close() |
| 6569 |
} |
| 6570 |
t.tui.Close() |
| 6571 |
code = getCode() |
| 6572 |
if code <= ExitNoMatch && t.history != nil { |
| 6573 |
t.history.append(string(t.input)) |
| 6574 |
} |
| 6575 |
t.runningCmds.ForEach(func(cmd *runningCmd) { |
| 6576 |
util.KillCommand(cmd.cmd) |
| 6577 |
removeFiles(cmd.tempFiles) |
| 6578 |
}) |
| 6579 |
running = false |
| 6580 |
t.mutex.Unlock() |
| 6581 |
} |
| 6582 |
|
| 6583 |
for running { |
| 6584 |
t.reqBox.Wait(func(events *util.Events) { |
| 6585 |
defer events.Clear() |
| 6586 |
|
| 6587 |
// Sort events. |
| 6588 |
// e.g. Make sure that reqPrompt is processed before reqInfo |
| 6589 |
keys := make([]int, 0, len(*events)) |
| 6590 |
for key := range *events { |
| 6591 |
keys = append(keys, int(key)) |
| 6592 |
} |
| 6593 |
sort.Ints(keys) |
| 6594 |
|
| 6595 |
// t.uiMutex must be locked first to avoid deadlock. Execute actions |
| 6596 |
// will 1. unlock t.mutex to allow GET endpoint and 2. lock t.uiMutex |
| 6597 |
// to block rendering during the execution. |
| 6598 |
// |
| 6599 |
// T1 T2 (good) | T1 T2 (bad) |
| 6600 |
// L t.uiMutex | |
| 6601 |
// L t.mutex | L t.mutex |
| 6602 |
// U t.mutex | U t.mutex |
| 6603 |
// L t.mutex | L t.mutex |
| 6604 |
// U t.mutex | L t.uiMutex |
| 6605 |
// U t.uiMutex | L t.uiMutex!! |
| 6606 |
// L t.uiMutex | |
| 6607 |
// | L t.mutex!! |
| 6608 |
// L t.mutex | U t.uiMutex |
| 6609 |
// U t.uiMutex | |
| 6610 |
t.uiMutex.Lock() |
| 6611 |
t.mutex.Lock() |
| 6612 |
info := false |
| 6613 |
header := false |
| 6614 |
footer := false |
| 6615 |
for _, key := range keys { |
| 6616 |
req := util.EventType(key) |
| 6617 |
value := (*events)[req] |
| 6618 |
switch req { |
| 6619 |
case reqPrompt: |
| 6620 |
t.printPrompt() |
| 6621 |
if t.infoStyle == infoInline || t.infoStyle == infoInlineRight { |
| 6622 |
info = true |
| 6623 |
} |
| 6624 |
case reqInfo: |
| 6625 |
info = true |
| 6626 |
case reqList: |
| 6627 |
t.printList() |
| 6628 |
currentIndex := t.currentIndex() |
| 6629 |
if t.track.Current() && t.track.index != currentIndex { |
| 6630 |
t.track = trackDisabled |
| 6631 |
info = true |
| 6632 |
} |
| 6633 |
focusChanged := focusedIndex != currentIndex |
| 6634 |
if (t.hasFocusActions || t.infoCommand != "") && focusChanged && currentIndex != t.lastFocus { |
| 6635 |
t.lastFocus = currentIndex |
| 6636 |
t.eventChan <- tui.Focus.AsEvent() |
| 6637 |
if t.infoCommand != "" { |
| 6638 |
info = true |
| 6639 |
} |
| 6640 |
} |
| 6641 |
if focusChanged || version != t.version { |
| 6642 |
version = t.version |
| 6643 |
focusedIndex = currentIndex |
| 6644 |
refreshPreview(t.previewOpts.command) |
| 6645 |
} |
| 6646 |
case reqJump: |
| 6647 |
if t.merger.Length() == 0 { |
| 6648 |
t.jumping = jumpDisabled |
| 6649 |
} |
| 6650 |
t.printList() |
| 6651 |
case reqHeader: |
| 6652 |
header = true |
| 6653 |
case reqFooter: |
| 6654 |
footer = true |
| 6655 |
case reqActivate: |
| 6656 |
t.suppress = false |
| 6657 |
if t.hasPreviewer() { |
| 6658 |
t.previewBox.Set(reqPreviewReady, nil) |
| 6659 |
} |
| 6660 |
case reqRedrawInputLabel: |
| 6661 |
t.printLabel(t.inputBorder, t.inputLabel, t.inputLabelOpts, t.inputLabelLen, t.inputBorderShape, true) |
| 6662 |
case reqRedrawHeaderLabel: |
| 6663 |
if t.headerBorderShape == tui.BorderInline { |
| 6664 |
// Inline labels sit on the separator inside wborder; re-run the |
| 6665 |
// full layout to repaint the separator + label together. |
| 6666 |
t.printAll() |
| 6667 |
} else { |
| 6668 |
t.printLabel(t.headerBorder, t.headerLabel, t.headerLabelOpts, t.headerLabelLen, t.headerBorderShape, true) |
| 6669 |
} |
| 6670 |
case reqRedrawFooterLabel: |
| 6671 |
if t.footerBorderShape == tui.BorderInline { |
| 6672 |
t.printAll() |
| 6673 |
} else { |
| 6674 |
t.printLabel(t.footerBorder, t.footerLabel, t.footerLabelOpts, t.footerLabelLen, t.footerBorderShape, true) |
| 6675 |
} |
| 6676 |
case reqRedrawListLabel: |
| 6677 |
// When inline sections are active, the label's bg depends on which |
| 6678 |
// section owns the adjacent edge. Rerun the layout to reuse that |
| 6679 |
// logic rather than duplicating it here. |
| 6680 |
if t.headerBorderShape == tui.BorderInline || t.headerLinesShape == tui.BorderInline || t.footerBorderShape == tui.BorderInline { |
| 6681 |
t.printAll() |
| 6682 |
} else { |
| 6683 |
t.printLabel(t.wborder, t.listLabel, t.listLabelOpts, t.listLabelLen, t.listBorderShape, true) |
| 6684 |
} |
| 6685 |
case reqRedrawBorderLabel: |
| 6686 |
t.printLabel(t.border, t.borderLabel, t.borderLabelOpts, t.borderLabelLen, t.borderShape, true) |
| 6687 |
case reqRedrawPreviewLabel: |
| 6688 |
t.printLabel(t.pborder, t.previewLabel, t.previewLabelOpts, t.previewLabelLen, t.activePreviewOpts.Border(t.layout), true) |
| 6689 |
case reqReinit, reqResize, reqFullRedraw, reqRedraw: |
| 6690 |
if req == reqReinit { |
| 6691 |
t.tui.Resume(t.fullscreen, true) |
| 6692 |
} |
| 6693 |
if req == reqResize { |
| 6694 |
t.termSize = t.tui.Size() |
| 6695 |
} |
| 6696 |
wasHidden := t.pwindow == nil |
| 6697 |
if req == reqRedraw { |
| 6698 |
t.printAll() |
| 6699 |
} else { |
| 6700 |
t.fullRedraw() |
| 6701 |
} |
| 6702 |
if wasHidden && t.hasPreviewWindow() { |
| 6703 |
refreshPreview(t.previewOpts.command) |
| 6704 |
} |
| 6705 |
if req == reqResize && t.hasResizeActions { |
| 6706 |
t.eventChan <- tui.Resize.AsEvent() |
| 6707 |
} |
| 6708 |
case reqClose: |
| 6709 |
exit(func() int { |
| 6710 |
if t.output() { |
| 6711 |
return ExitOk |
| 6712 |
} |
| 6713 |
return ExitNoMatch |
| 6714 |
}) |
| 6715 |
return |
| 6716 |
case reqPreviewDisplay: |
| 6717 |
result := value.(previewResult) |
| 6718 |
if t.previewer.version != result.version { |
| 6719 |
t.previewer.version = result.version |
| 6720 |
t.previewer.following.Force(t.activePreviewOpts.follow) |
| 6721 |
if t.previewer.following.Enabled() { |
| 6722 |
t.previewer.offset = 0 |
| 6723 |
} |
| 6724 |
} |
| 6725 |
t.previewer.lines = result.lines |
| 6726 |
t.previewer.spinner = result.spinner |
| 6727 |
if t.hasPreviewWindow() && t.previewer.following.Enabled() { |
| 6728 |
t.previewer.offset = t.followOffset() |
| 6729 |
} else if result.offset >= 0 { |
| 6730 |
t.previewer.offset = util.Constrain(result.offset, t.activePreviewOpts.headerLines, len(t.previewer.lines)-1) |
| 6731 |
} |
| 6732 |
t.printPreview() |
| 6733 |
case reqPreviewRefresh: |
| 6734 |
t.printPreview() |
| 6735 |
case reqPreviewDelayed: |
| 6736 |
t.previewer.version = value.(int64) |
| 6737 |
t.printPreviewDelayed() |
| 6738 |
case reqPrintQuery: |
| 6739 |
exit(func() int { |
| 6740 |
t.printer(string(t.input)) |
| 6741 |
return ExitOk |
| 6742 |
}) |
| 6743 |
return |
| 6744 |
case reqBecome: |
| 6745 |
exit(func() int { return ExitBecome }) |
| 6746 |
return |
| 6747 |
case reqQuit: |
| 6748 |
exit(func() int { return ExitInterrupt }) |
| 6749 |
return |
| 6750 |
case reqFatal: |
| 6751 |
exit(func() int { return ExitError }) |
| 6752 |
return |
| 6753 |
} |
| 6754 |
} |
| 6755 |
if (info || header || footer) && !t.resizeIfNeeded() { |
| 6756 |
if info { |
| 6757 |
t.printInfo() |
| 6758 |
} |
| 6759 |
if header { |
| 6760 |
t.printHeader() |
| 6761 |
} |
| 6762 |
if footer { |
| 6763 |
t.printFooter() |
| 6764 |
} |
| 6765 |
} |
| 6766 |
// Hide the cursor while the debounced waiting feedback is shown |
| 6767 |
if !t.inputless && !t.trackBlocked && t.waitFeedback() { |
| 6768 |
t.tui.HideCursor() |
| 6769 |
} |
| 6770 |
t.flush() |
| 6771 |
t.mutex.Unlock() |
| 6772 |
t.uiMutex.Unlock() |
| 6773 |
}) |
| 6774 |
} |
| 6775 |
|
| 6776 |
t.running.Set(false) |
| 6777 |
t.killPreview() |
| 6778 |
cancel() |
| 6779 |
t.eventBox.Set(EvtQuit, quitSignal{code, nil}) |
| 6780 |
}() |
| 6781 |
|
| 6782 |
looping := true |
| 6783 |
barrier := make(chan bool) |
| 6784 |
go func() { |
| 6785 |
for { |
| 6786 |
select { |
| 6787 |
case <-ctx.Done(): |
| 6788 |
return |
| 6789 |
case <-barrier: |
| 6790 |
} |
| 6791 |
select { |
| 6792 |
case <-ctx.Done(): |
| 6793 |
return |
| 6794 |
case t.keyChan <- t.tui.GetChar(t.listenAddr != nil): |
| 6795 |
} |
| 6796 |
} |
| 6797 |
}() |
| 6798 |
t.startTimers(ctx) |
| 6799 |
previewDraggingPos := -1 |
| 6800 |
barDragging := false |
| 6801 |
pbarDragging := false |
| 6802 |
pborderDragging := -1 |
| 6803 |
wasDown := false |
| 6804 |
pmx, pmy := -1, -1 |
| 6805 |
needBarrier := true |
| 6806 |
|
| 6807 |
// If an action is bound to 'start', we're going to process it before reading |
| 6808 |
// user input. |
| 6809 |
if !t.hasStartActions { |
| 6810 |
barrier <- true |
| 6811 |
needBarrier = false |
| 6812 |
} |
| 6813 |
|
| 6814 |
// These variables are defined outside the loop to be accessible from closures. |
| 6815 |
// In particular, async bg-transform callbacks run in a later iteration than |
| 6816 |
// the one that scheduled them, but still need to mutate state that the |
| 6817 |
// loop-end reload/event dispatch reads. |
| 6818 |
events := []util.EventType{} |
| 6819 |
changed := false |
| 6820 |
var newNth *[]Range |
| 6821 |
var newWithNth *withNthSpec |
| 6822 |
var newHeaderLines *int |
| 6823 |
var newCommand *commandSpec |
| 6824 |
var reloadSync bool |
| 6825 |
var denylist []int32 |
| 6826 |
// True while running bg-transform callbacks. Declared outside the loop |
| 6827 |
// because callbacks invoke the doActions closure of the iteration that |
| 6828 |
// scheduled them, not the one executing actAsync. |
| 6829 |
inBgCallback := false |
| 6830 |
req := func(evts ...util.EventType) { |
| 6831 |
for _, event := range evts { |
| 6832 |
events = append(events, event) |
| 6833 |
if isTerminalEvent(event) { |
| 6834 |
looping = false |
| 6835 |
} |
| 6836 |
} |
| 6837 |
} |
| 6838 |
|
| 6839 |
// The main event loop |
| 6840 |
for loopIndex := int64(0); looping; loopIndex++ { |
| 6841 |
events = []util.EventType{} |
| 6842 |
changed = false |
| 6843 |
newNth = nil |
| 6844 |
newWithNth = nil |
| 6845 |
newHeaderLines = nil |
| 6846 |
newCommand = nil |
| 6847 |
reloadSync = false |
| 6848 |
denylist = nil |
| 6849 |
beof := false |
| 6850 |
queryChanged := false |
| 6851 |
|
| 6852 |
// Special handling of --sync. Activate the interface on the second tick. |
| 6853 |
if loopIndex == 1 && t.deferActivation() { |
| 6854 |
t.reqBox.Set(reqActivate, nil) |
| 6855 |
} |
| 6856 |
|
| 6857 |
if loopIndex > 0 && needBarrier { |
| 6858 |
barrier <- true |
| 6859 |
needBarrier = false |
| 6860 |
} |
| 6861 |
|
| 6862 |
var event tui.Event |
| 6863 |
actions := []*action{} |
| 6864 |
callbacks := []versionedCallback{} |
| 6865 |
select { |
| 6866 |
case event = <-t.keyChan: |
| 6867 |
needBarrier = true |
| 6868 |
case event = <-t.timerChan: |
| 6869 |
case event = <-t.eventChan: |
| 6870 |
// Drain channel to process all queued events at once without rendering |
| 6871 |
// the intermediate states |
| 6872 |
Drain: |
| 6873 |
for { |
| 6874 |
if eventActions, prs := t.keymap[event]; prs { |
| 6875 |
actions = append(actions, eventActions...) |
| 6876 |
} |
| 6877 |
for { |
| 6878 |
select { |
| 6879 |
case event = <-t.eventChan: |
| 6880 |
continue Drain |
| 6881 |
default: |
| 6882 |
break Drain |
| 6883 |
} |
| 6884 |
} |
| 6885 |
} |
| 6886 |
case serverActions := <-t.serverInputChan: |
| 6887 |
event = tui.Invalid.AsEvent() |
| 6888 |
if t.listenAddr == nil || t.listenAddr.IsLocal() || t.listenUnsafe { |
| 6889 |
actions = serverActions |
| 6890 |
} else { |
| 6891 |
for _, action := range serverActions { |
| 6892 |
if !processExecution(action.t) { |
| 6893 |
actions = append(actions, action) |
| 6894 |
} |
| 6895 |
} |
| 6896 |
} |
| 6897 |
for _, action := range actions { |
| 6898 |
if action.t == actExecute { |
| 6899 |
t.tui.CancelGetChar() |
| 6900 |
break |
| 6901 |
} |
| 6902 |
} |
| 6903 |
|
| 6904 |
case callback := <-t.callbackChan: |
| 6905 |
event = tui.Invalid.AsEvent() |
| 6906 |
actions = append(actions, &action{t: actAsync}) |
| 6907 |
callbacks = append(callbacks, callback) |
| 6908 |
DrainCallback: |
| 6909 |
for { |
| 6910 |
select { |
| 6911 |
case callback = <-t.callbackChan: |
| 6912 |
callbacks = append(callbacks, callback) |
| 6913 |
continue DrainCallback |
| 6914 |
default: |
| 6915 |
break DrainCallback |
| 6916 |
} |
| 6917 |
} |
| 6918 |
} |
| 6919 |
|
| 6920 |
t.mutex.Lock() |
| 6921 |
// Ignore --expect keys while wait-blocked like the rest of the input |
| 6922 |
if !t.wait.blocked { |
| 6923 |
for key, ret := range t.expect { |
| 6924 |
if keyMatch(key, event) { |
| 6925 |
t.pressed = ret |
| 6926 |
t.mutex.Unlock() |
| 6927 |
t.reqBox.Set(reqClose, nil) |
| 6928 |
return nil |
| 6929 |
} |
| 6930 |
} |
| 6931 |
} |
| 6932 |
triggering := map[tui.Event]struct{}{} |
| 6933 |
previousInput := t.input |
| 6934 |
previousCx := t.cx |
| 6935 |
previousVersion := t.version |
| 6936 |
if event.Type < tui.Invalid { |
| 6937 |
t.lastKey = event.KeyName() |
| 6938 |
t.lastActivity = time.Now() |
| 6939 |
} |
| 6940 |
updatePreviewWindow := func(forcePreview bool) { |
| 6941 |
t.resizeWindows(forcePreview, false) |
| 6942 |
req(reqPrompt, reqList, reqInfo, reqHeader, reqFooter) |
| 6943 |
} |
| 6944 |
toggle := func() bool { |
| 6945 |
current := t.currentItem() |
| 6946 |
if current != nil && t.toggleItem(current) { |
| 6947 |
req(reqInfo) |
| 6948 |
return true |
| 6949 |
} |
| 6950 |
return false |
| 6951 |
} |
| 6952 |
scrollPreviewTo := func(newOffset int) { |
| 6953 |
if !t.previewer.scrollable { |
| 6954 |
return |
| 6955 |
} |
| 6956 |
numLines := len(t.previewer.lines) |
| 6957 |
headerLines := t.activePreviewOpts.headerLines |
| 6958 |
if t.activePreviewOpts.cycle { |
| 6959 |
offsetRange := numLines - headerLines |
| 6960 |
newOffset = ((newOffset-headerLines)+offsetRange)%offsetRange + headerLines |
| 6961 |
} |
| 6962 |
newOffset = util.Constrain(newOffset, headerLines, numLines-1) |
| 6963 |
if t.previewer.offset != newOffset { |
| 6964 |
t.previewer.offset = newOffset |
| 6965 |
t.previewer.following.Set(t.previewer.offset >= numLines-(t.pwindow.Height()-headerLines)) |
| 6966 |
req(reqPreviewRefresh) |
| 6967 |
} |
| 6968 |
} |
| 6969 |
scrollPreviewBy := func(amount int) { |
| 6970 |
scrollPreviewTo(t.previewer.offset + amount) |
| 6971 |
} |
| 6972 |
|
| 6973 |
actionsFor := func(eventType tui.EventType) []*action { |
| 6974 |
return t.keymap[eventType.AsEvent()] |
| 6975 |
} |
| 6976 |
|
| 6977 |
var doAction func(*action) bool |
| 6978 |
doActions := func(actions []*action) bool { |
| 6979 |
// Snapshot to detect query edits in this batch that trigger a |
| 6980 |
// search at loop end without setting 'changed'. String copy: |
| 6981 |
// edits mutate t.input in place. |
| 6982 |
queryBefore := string(t.input) |
| 6983 |
for iter := 0; iter <= maxFocusEvents; iter++ { |
| 6984 |
currentIndex := t.currentIndex() |
| 6985 |
for i, action := range actions { |
| 6986 |
if action.t == actWait { |
| 6987 |
// Already waiting. Actions parsed from a bg-transform |
| 6988 |
// result join the current wait; user input can't reset |
| 6989 |
// the blocked state |
| 6990 |
if t.wait.blocked { |
| 6991 |
if inBgCallback { |
| 6992 |
t.wait.pending = append(t.wait.pending, actions[i+1:]...) |
| 6993 |
} |
| 6994 |
return true |
| 6995 |
} |
| 6996 |
// Block if search is in progress or will be triggered |
| 6997 |
if changed || newCommand != nil || t.wait.searching || queryBefore != string(t.input) { |
| 6998 |
t.blockWait(actions[i+1:]) |
| 6999 |
return true |
| 7000 |
} |
| 7001 |
// No search, wait is a no-op; continue to next action |
| 7002 |
continue |
| 7003 |
} |
| 7004 |
blockedBefore := t.wait.blocked |
| 7005 |
if !doAction(action) { |
| 7006 |
return false |
| 7007 |
} |
| 7008 |
// If this action armed the wait through a nested list |
| 7009 |
// (e.g. via trigger), defer the rest of this list too |
| 7010 |
if !blockedBefore && t.wait.blocked { |
| 7011 |
t.wait.pending = append(t.wait.pending, actions[i+1:]...) |
| 7012 |
return true |
| 7013 |
} |
| 7014 |
// A terminal action performed. We should stop processing more. |
| 7015 |
if !looping { |
| 7016 |
break |
| 7017 |
} |
| 7018 |
} |
| 7019 |
|
| 7020 |
if onFocus, prs := t.keymap[tui.Focus.AsEvent()]; prs && iter < maxFocusEvents { |
| 7021 |
if newIndex := t.currentIndex(); newIndex != currentIndex { |
| 7022 |
t.lastFocus = newIndex |
| 7023 |
if t.infoCommand != "" { |
| 7024 |
req(reqInfo) |
| 7025 |
} |
| 7026 |
actions = onFocus |
| 7027 |
continue |
| 7028 |
} |
| 7029 |
} |
| 7030 |
break |
| 7031 |
} |
| 7032 |
return true |
| 7033 |
} |
| 7034 |
doAction = func(a *action) bool { |
| 7035 |
// Keep track of the current query before the action is executed, |
| 7036 |
// so we can restore it when the input section is hidden (--no-input). |
| 7037 |
// * By doing this, we don't have to add a conditional branch to each |
| 7038 |
// query modifying action. |
| 7039 |
// * We restore the query after each action instead of after a set of |
| 7040 |
// actions to allow changing the query even when the input is hidden |
| 7041 |
// e.g. fzf --no-input --bind 'space:show-input+change-query(foo)+hide-input' |
| 7042 |
currentInput := t.input |
| 7043 |
capture := func(firstLineOnly bool, callback func(string)) { |
| 7044 |
if a.t >= actBgTransform { |
| 7045 |
// bg-transform-* |
| 7046 |
t.captureAsync(*a, firstLineOnly, callback) |
| 7047 |
} else if a.t >= actTransform { |
| 7048 |
// transform-* |
| 7049 |
if firstLineOnly { |
| 7050 |
callback(t.captureLine(a.a)) |
| 7051 |
} else { |
| 7052 |
callback(t.captureLines(a.a)) |
| 7053 |
} |
| 7054 |
} else { |
| 7055 |
// change-* |
| 7056 |
callback(a.a) |
| 7057 |
} |
| 7058 |
} |
| 7059 |
// Actions that run even while wait/track-blocked: bg-transform |
| 7060 |
// callbacks and their parsed actions (results of processes |
| 7061 |
// started before the block), and bracketed paste bookkeeping (a |
| 7062 |
// swallowed paste-end would leave t.pasting set forever). |
| 7063 |
passthrough := inBgCallback || a.t == actAsync || |
| 7064 |
a.t == actBracketedPasteBegin || a.t == actBracketedPasteEnd |
| 7065 |
// When wait-blocked, only allow abort/cancel |
| 7066 |
if t.wait.blocked && !passthrough { |
| 7067 |
if a.t == actAbort || a.t == actCancel { |
| 7068 |
t.cancelWait() |
| 7069 |
req(reqPrompt, reqInfo) |
| 7070 |
} |
| 7071 |
return true |
| 7072 |
} |
| 7073 |
// When track-blocked, only allow abort/cancel and track-disabling actions |
| 7074 |
if t.trackBlocked && !passthrough && a.t != actToggleTrack && a.t != actToggleTrackCurrent && a.t != actUntrackCurrent { |
| 7075 |
if a.t == actAbort || a.t == actCancel { |
| 7076 |
t.unblockTrack() |
| 7077 |
req(reqPrompt, reqInfo) |
| 7078 |
} |
| 7079 |
return true |
| 7080 |
} |
| 7081 |
Action: |
| 7082 |
switch a.t { |
| 7083 |
case actIgnore, actStart, actClick: |
| 7084 |
case actAsync: |
| 7085 |
inBgCallback = true |
| 7086 |
for _, callback := range callbacks { |
| 7087 |
if t.bgVersion == callback.version { |
| 7088 |
callback.callback() |
| 7089 |
} |
| 7090 |
} |
| 7091 |
inBgCallback = false |
| 7092 |
case actBecome: |
| 7093 |
valid, list := t.buildPlusList(a.a, false) |
| 7094 |
if valid { |
| 7095 |
// We do not remove temp files in this case |
| 7096 |
command, _ := t.replacePlaceholder(a.a, false, string(t.input), list) |
| 7097 |
t.tui.Close() |
| 7098 |
if t.history != nil { |
| 7099 |
t.history.append(string(t.input)) |
| 7100 |
} |
| 7101 |
|
| 7102 |
if len(t.proxyScript) > 0 { |
| 7103 |
data := strings.Join(append([]string{command}, t.environ()...), "\x00") |
| 7104 |
os.WriteFile(t.proxyScript+becomeSuffix, []byte(data), 0600) |
| 7105 |
req(reqBecome) |
| 7106 |
} else { |
| 7107 |
t.executor.Become(t.ttyin, t.environ(), command) |
| 7108 |
} |
| 7109 |
} |
| 7110 |
case actBell: |
| 7111 |
t.tui.Bell() |
| 7112 |
case actExcludeMulti: |
| 7113 |
if len(t.selected) > 0 { |
| 7114 |
for _, item := range t.sortSelected() { |
| 7115 |
denylist = append(denylist, item.item.Index()) |
| 7116 |
} |
| 7117 |
// Clear selected items |
| 7118 |
t.selected = make(map[int32]selectedItem) |
| 7119 |
t.version++ |
| 7120 |
} else { |
| 7121 |
item := t.currentItem() |
| 7122 |
if item != nil { |
| 7123 |
denylist = append(denylist, item.Index()) |
| 7124 |
} |
| 7125 |
} |
| 7126 |
changed = true |
| 7127 |
case actExclude: |
| 7128 |
if item := t.currentItem(); item != nil { |
| 7129 |
denylist = append(denylist, item.Index()) |
| 7130 |
t.deselectItem(item) |
| 7131 |
changed = true |
| 7132 |
} |
| 7133 |
case actExecute, actExecuteSilent: |
| 7134 |
t.executeCommand(a.a, false, a.t == actExecuteSilent, false, false, "") |
| 7135 |
case actExecuteMulti: |
| 7136 |
t.executeCommand(a.a, true, false, false, false, "") |
| 7137 |
case actInvalid: |
| 7138 |
t.mutex.Unlock() |
| 7139 |
return false |
| 7140 |
case actBracketedPasteBegin: |
| 7141 |
// Clone: []rune(t.input) would alias t.input, and in-place |
| 7142 |
// query edits during the paste would corrupt the snapshot |
| 7143 |
current := slices.Clone(t.input) |
| 7144 |
t.pasting = ¤t |
| 7145 |
case actBracketedPasteEnd: |
| 7146 |
if t.pasting != nil { |
| 7147 |
queryChanged = string(t.input) != string(*t.pasting) |
| 7148 |
t.pasting = nil |
| 7149 |
} |
| 7150 |
case actTogglePreview, actShowPreview, actHidePreview: |
| 7151 |
var act bool |
| 7152 |
switch a.t { |
| 7153 |
case actShowPreview: |
| 7154 |
act = !t.hasPreviewWindow() && len(t.previewOpts.command) > 0 |
| 7155 |
case actHidePreview: |
| 7156 |
act = t.hasPreviewWindow() |
| 7157 |
case actTogglePreview: |
| 7158 |
act = t.hasPreviewWindow() || len(t.previewOpts.command) > 0 |
| 7159 |
} |
| 7160 |
if act { |
| 7161 |
t.activePreviewOpts.Toggle() |
| 7162 |
updatePreviewWindow(false) |
| 7163 |
if t.canPreview() { |
| 7164 |
valid, list := t.buildPlusList(t.previewOpts.command, false) |
| 7165 |
if valid { |
| 7166 |
t.cancelPreview() |
| 7167 |
t.previewBox.Set(reqPreviewEnqueue, |
| 7168 |
previewRequest{t.previewOpts.command, t.evaluateScrollOffset(), list, t.environForPreview(), string(t.input)}) |
| 7169 |
} |
| 7170 |
} else { |
| 7171 |
// Discard the preview content so that it won't accidentally appear |
| 7172 |
// when preview window is re-enabled and previewDelay is triggered |
| 7173 |
t.previewer.lines = nil |
| 7174 |
|
| 7175 |
// Also kill the preview process if it's still running |
| 7176 |
t.cancelPreview() |
| 7177 |
} |
| 7178 |
} |
| 7179 |
case actTogglePreviewWrap, actTogglePreviewWrapWord: |
| 7180 |
if t.hasPreviewWindow() { |
| 7181 |
if a.t == actTogglePreviewWrapWord { |
| 7182 |
t.activePreviewOpts.wrapWord = !t.activePreviewOpts.wrapWord |
| 7183 |
t.activePreviewOpts.wrap = t.activePreviewOpts.wrapWord |
| 7184 |
} else { |
| 7185 |
t.activePreviewOpts.wrap = !t.activePreviewOpts.wrap |
| 7186 |
if !t.activePreviewOpts.wrap { |
| 7187 |
t.activePreviewOpts.wrapWord = false |
| 7188 |
} |
| 7189 |
} |
| 7190 |
// Reset preview version so that full redraw occurs |
| 7191 |
t.previewed.version = 0 |
| 7192 |
req(reqPreviewRefresh) |
| 7193 |
} |
| 7194 |
case actTransformPrompt, actBgTransformPrompt: |
| 7195 |
capture(true, func(prompt string) { |
| 7196 |
t.promptString = prompt |
| 7197 |
t.prompt, t.promptLen = t.parsePrompt(prompt) |
| 7198 |
req(reqPrompt) |
| 7199 |
}) |
| 7200 |
case actTransformQuery, actBgTransformQuery: |
| 7201 |
capture(true, func(query string) { |
| 7202 |
t.input = []rune(query) |
| 7203 |
t.cx = len(t.input) |
| 7204 |
}) |
| 7205 |
case actToggleSort: |
| 7206 |
t.sort = !t.sort |
| 7207 |
changed = true |
| 7208 |
case actPreviewTop: |
| 7209 |
if t.hasPreviewWindow() { |
| 7210 |
scrollPreviewTo(0) |
| 7211 |
} |
| 7212 |
case actPreviewBottom: |
| 7213 |
if t.hasPreviewWindow() { |
| 7214 |
scrollPreviewTo(len(t.previewer.lines) - t.pwindow.Height()) |
| 7215 |
} |
| 7216 |
case actPreviewUp: |
| 7217 |
if t.hasPreviewWindow() { |
| 7218 |
scrollPreviewBy(-1) |
| 7219 |
} |
| 7220 |
case actPreviewDown: |
| 7221 |
if t.hasPreviewWindow() { |
| 7222 |
scrollPreviewBy(1) |
| 7223 |
} |
| 7224 |
case actPreviewPageUp: |
| 7225 |
if t.hasPreviewWindow() { |
| 7226 |
scrollPreviewBy(-t.pwindow.Height()) |
| 7227 |
} |
| 7228 |
case actPreviewPageDown: |
| 7229 |
if t.hasPreviewWindow() { |
| 7230 |
scrollPreviewBy(t.pwindow.Height()) |
| 7231 |
} |
| 7232 |
case actPreviewHalfPageUp: |
| 7233 |
if t.hasPreviewWindow() { |
| 7234 |
scrollPreviewBy(-t.pwindow.Height() / 2) |
| 7235 |
} |
| 7236 |
case actPreviewHalfPageDown: |
| 7237 |
if t.hasPreviewWindow() { |
| 7238 |
scrollPreviewBy(t.pwindow.Height() / 2) |
| 7239 |
} |
| 7240 |
case actBeginningOfLine: |
| 7241 |
t.cx = 0 |
| 7242 |
t.xoffset = 0 |
| 7243 |
case actBackwardChar: |
| 7244 |
if t.cx > 0 { |
| 7245 |
t.cx-- |
| 7246 |
} |
| 7247 |
case actPrintQuery: |
| 7248 |
req(reqPrintQuery) |
| 7249 |
case actChangeHeaderLines, actTransformHeaderLines, actBgTransformHeaderLines: |
| 7250 |
capture(true, func(expr string) { |
| 7251 |
if n, err := strconv.Atoi(expr); err == nil && n >= 0 && n != t.headerLines { |
| 7252 |
t.headerLines = n |
| 7253 |
newHeaderLines = &n |
| 7254 |
changed = true |
| 7255 |
// Deselect items that are now part of the header |
| 7256 |
for idx := range t.selected { |
| 7257 |
if int(idx) < n { |
| 7258 |
delete(t.selected, idx) |
| 7259 |
} |
| 7260 |
} |
| 7261 |
// Tell UpdateList to reposition cursor to the current item |
| 7262 |
t.targetIndex = t.currentIndex() |
| 7263 |
req(reqList, reqPrompt, reqInfo, reqHeader) |
| 7264 |
} |
| 7265 |
}) |
| 7266 |
case actChangeMulti: |
| 7267 |
multi := t.multi |
| 7268 |
if a.a == "" { |
| 7269 |
multi = maxMulti |
| 7270 |
} else if n, e := strconv.Atoi(a.a); e == nil && n >= 0 { |
| 7271 |
multi = n |
| 7272 |
} |
| 7273 |
if t.multi > 0 && multi != t.multi { |
| 7274 |
t.selected = make(map[int32]selectedItem) |
| 7275 |
t.version++ |
| 7276 |
} |
| 7277 |
t.multi = multi |
| 7278 |
req(reqList, reqInfo) |
| 7279 |
case actChangeNth, actTransformNth, actBgTransformNth: |
| 7280 |
capture(true, func(expr string) { |
| 7281 |
// Split nth expression |
| 7282 |
tokens := strings.Split(expr, "|") |
| 7283 |
if nth, err := splitNth(tokens[0]); err == nil || len(expr) == 0 { |
| 7284 |
// Changed |
| 7285 |
newNth = &nth |
| 7286 |
} else { |
| 7287 |
// The default |
| 7288 |
newNth = &t.nth |
| 7289 |
} |
| 7290 |
// Cycle |
| 7291 |
if len(tokens) > 1 { |
| 7292 |
a.a = strings.Join(append(tokens[1:], tokens[0]), "|") |
| 7293 |
} |
| 7294 |
if !compareRanges(t.nthCurrent, *newNth) { |
| 7295 |
changed = true |
| 7296 |
t.nthCurrent = *newNth |
| 7297 |
t.forceRerenderList() |
| 7298 |
} |
| 7299 |
}) |
| 7300 |
case actChangeWithNth, actTransformWithNth, actBgTransformWithNth: |
| 7301 |
if !t.withNthEnabled { |
| 7302 |
break Action |
| 7303 |
} |
| 7304 |
capture(true, func(expr string) { |
| 7305 |
tokens := strings.Split(expr, "|") |
| 7306 |
withNthExpr := tokens[0] |
| 7307 |
if len(tokens) > 1 { |
| 7308 |
a.a = strings.Join(append(tokens[1:], tokens[0]), "|") |
| 7309 |
} |
| 7310 |
// Empty value restores the default --with-nth |
| 7311 |
if len(withNthExpr) == 0 { |
| 7312 |
withNthExpr = t.withNthDefault |
| 7313 |
} |
| 7314 |
if withNthExpr != t.withNthExpr { |
| 7315 |
if factory, err := nthTransformer(withNthExpr); err == nil { |
| 7316 |
newWithNth = &withNthSpec{fn: factory(t.delimiter)} |
| 7317 |
} else { |
| 7318 |
return |
| 7319 |
} |
| 7320 |
t.withNthExpr = withNthExpr |
| 7321 |
t.filterSelection = true |
| 7322 |
changed = true |
| 7323 |
t.clearNumLinesCache() |
| 7324 |
t.forceRerenderList() |
| 7325 |
} |
| 7326 |
}) |
| 7327 |
case actChangeQuery: |
| 7328 |
t.input = []rune(a.a) |
| 7329 |
t.cx = len(t.input) |
| 7330 |
case actChangeHeader, actTransformHeader, actBgTransformHeader: |
| 7331 |
capture(false, func(header string) { |
| 7332 |
if t.changeHeader(header) { |
| 7333 |
// resizeIfNeeded() tolerates a shorter-than-wanted inline |
| 7334 |
// window, so a length change can leave the inline slot |
| 7335 |
// stale. Force a redraw to re-run the layout. Non-inline |
| 7336 |
// shapes are handled by resizeIfNeeded. |
| 7337 |
if t.headerBorderShape == tui.BorderInline { |
| 7338 |
req(reqRedraw) |
| 7339 |
} else { |
| 7340 |
req(reqList, reqPrompt, reqInfo) |
| 7341 |
} |
| 7342 |
} |
| 7343 |
req(reqHeader) |
| 7344 |
}) |
| 7345 |
case actChangeFooter, actTransformFooter, actBgTransformFooter: |
| 7346 |
capture(false, func(footer string) { |
| 7347 |
if t.changeFooter(footer) && t.footerBorderShape == tui.BorderInline { |
| 7348 |
// resizeIfNeeded() tolerates a shorter-than-wanted inline |
| 7349 |
// window, so a length change can leave the inline slot |
| 7350 |
// stale. Force a redraw to re-run the layout. |
| 7351 |
req(reqRedraw) |
| 7352 |
} |
| 7353 |
req(reqFooter) |
| 7354 |
}) |
| 7355 |
case actChangeHeaderLabel, actTransformHeaderLabel, actBgTransformHeaderLabel: |
| 7356 |
capture(true, func(label string) { |
| 7357 |
t.headerLabelOpts.label = label |
| 7358 |
t.headerLabel, t.headerLabelLen = t.ansiLabelPrinter(label, &tui.ColHeaderLabel, false) |
| 7359 |
req(reqRedrawHeaderLabel) |
| 7360 |
}) |
| 7361 |
case actChangeFooterLabel, actTransformFooterLabel, actBgTransformFooterLabel: |
| 7362 |
capture(true, func(label string) { |
| 7363 |
t.footerLabelOpts.label = label |
| 7364 |
t.footerLabel, t.footerLabelLen = t.ansiLabelPrinter(label, &tui.ColFooterLabel, false) |
| 7365 |
req(reqRedrawFooterLabel) |
| 7366 |
}) |
| 7367 |
case actChangeInputLabel, actTransformInputLabel, actBgTransformInputLabel: |
| 7368 |
capture(true, func(label string) { |
| 7369 |
t.inputLabelOpts.label = label |
| 7370 |
if t.inputBorder != nil { |
| 7371 |
t.inputLabel, t.inputLabelLen = t.ansiLabelPrinter(label, &tui.ColInputLabel, false) |
| 7372 |
req(reqRedrawInputLabel) |
| 7373 |
} |
| 7374 |
}) |
| 7375 |
case actChangeListLabel, actTransformListLabel, actBgTransformListLabel: |
| 7376 |
capture(true, func(label string) { |
| 7377 |
t.listLabelOpts.label = label |
| 7378 |
if t.wborder != nil { |
| 7379 |
t.listLabel, t.listLabelLen = t.ansiLabelPrinter(label, &tui.ColListLabel, false) |
| 7380 |
req(reqRedrawListLabel) |
| 7381 |
} |
| 7382 |
}) |
| 7383 |
case actChangeBorderLabel, actTransformBorderLabel, actBgTransformBorderLabel: |
| 7384 |
capture(true, func(label string) { |
| 7385 |
t.borderLabelOpts.label = label |
| 7386 |
if t.border != nil { |
| 7387 |
t.borderLabel, t.borderLabelLen = t.ansiLabelPrinter(label, &tui.ColBorderLabel, false) |
| 7388 |
req(reqRedrawBorderLabel) |
| 7389 |
} else if t.setNativeLabel != nil { |
| 7390 |
// fzf draws no border of its own; the label is on the |
| 7391 |
// native border of the floating pane |
| 7392 |
t.setNativeLabel(label) |
| 7393 |
} |
| 7394 |
}) |
| 7395 |
case actChangePreviewLabel, actTransformPreviewLabel, actBgTransformPreviewLabel: |
| 7396 |
capture(true, func(label string) { |
| 7397 |
t.previewLabelOpts.label = label |
| 7398 |
if t.pborder != nil { |
| 7399 |
t.previewLabel, t.previewLabelLen = t.ansiLabelPrinter(label, &tui.ColPreviewLabel, false) |
| 7400 |
req(reqRedrawPreviewLabel) |
| 7401 |
} |
| 7402 |
}) |
| 7403 |
case actTransform, actBgTransform: |
| 7404 |
capture(false, func(body string) { |
| 7405 |
// Allow 'put' if the triggering key is a printable character |
| 7406 |
if actions, err := parseSingleActionList(strings.Trim(body, "\r\n"), event.Printable()); err == nil { |
| 7407 |
// NOTE: We're not properly passing the return value here |
| 7408 |
doActions(actions) |
| 7409 |
} |
| 7410 |
}) |
| 7411 |
case actBgCancel: |
| 7412 |
t.bgVersion++ |
| 7413 |
t.runningCmds.ForEach(func(cmd *runningCmd) { |
| 7414 |
util.KillCommand(cmd.cmd) |
| 7415 |
}) |
| 7416 |
case actChangePrompt: |
| 7417 |
t.promptString = a.a |
| 7418 |
t.prompt, t.promptLen = t.parsePrompt(a.a) |
| 7419 |
req(reqPrompt) |
| 7420 |
case actPreview: |
| 7421 |
if !t.hasPreviewWindow() { |
| 7422 |
updatePreviewWindow(true) |
| 7423 |
} |
| 7424 |
refreshPreview(a.a) |
| 7425 |
case actRefreshPreview: |
| 7426 |
refreshPreview(t.previewOpts.command) |
| 7427 |
case actReplaceQuery: |
| 7428 |
current := t.currentItem() |
| 7429 |
if current != nil { |
| 7430 |
// ToRunes aliases the item text in rune mode, and the |
| 7431 |
// editing actions below append into t.input in place |
| 7432 |
t.input = append([]rune{}, current.text.ToRunes()...) |
| 7433 |
t.cx = len(t.input) |
| 7434 |
} |
| 7435 |
case actFatal: |
| 7436 |
req(reqFatal) |
| 7437 |
case actAbort: |
| 7438 |
req(reqQuit) |
| 7439 |
case actDeleteChar: |
| 7440 |
t.delChar() |
| 7441 |
case actDeleteCharEof: |
| 7442 |
if !t.delChar() && t.cx == 0 { |
| 7443 |
req(reqQuit) |
| 7444 |
} |
| 7445 |
case actEndOfLine: |
| 7446 |
t.cx = len(t.input) |
| 7447 |
case actCancel: |
| 7448 |
if len(t.input) == 0 { |
| 7449 |
req(reqQuit) |
| 7450 |
} else { |
| 7451 |
t.yanked = t.input |
| 7452 |
t.input = []rune{} |
| 7453 |
t.cx = 0 |
| 7454 |
} |
| 7455 |
case actBackwardDeleteCharEof: |
| 7456 |
if len(t.input) == 0 { |
| 7457 |
req(reqQuit) |
| 7458 |
} else if t.cx > 0 { |
| 7459 |
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...) |
| 7460 |
t.cx-- |
| 7461 |
} |
| 7462 |
case actForwardChar: |
| 7463 |
if t.cx < len(t.input) { |
| 7464 |
t.cx++ |
| 7465 |
} |
| 7466 |
case actBackwardDeleteChar: |
| 7467 |
beof = len(t.input) == 0 |
| 7468 |
if t.cx > 0 { |
| 7469 |
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...) |
| 7470 |
t.cx-- |
| 7471 |
} |
| 7472 |
case actSelectAll: |
| 7473 |
if t.multi > 0 { |
| 7474 |
// Limit the scope only to the matching items |
| 7475 |
for i := 0; i < t.resultMerger.Length(); i++ { |
| 7476 |
if !t.selectItem(t.resultMerger.Get(i).item) { |
| 7477 |
break |
| 7478 |
} |
| 7479 |
} |
| 7480 |
req(reqList, reqInfo) |
| 7481 |
} |
| 7482 |
case actDeselectAll: |
| 7483 |
if t.multi > 0 { |
| 7484 |
// Also limit the scope only to the matching items, while this may |
| 7485 |
// not be straightforward in raw mode. |
| 7486 |
for i := 0; i < t.resultMerger.Length() && len(t.selected) > 0; i++ { |
| 7487 |
t.deselectItem(t.resultMerger.Get(i).item) |
| 7488 |
} |
| 7489 |
req(reqList, reqInfo) |
| 7490 |
} |
| 7491 |
case actClose: |
| 7492 |
if t.hasPreviewWindow() { |
| 7493 |
t.activePreviewOpts.Toggle() |
| 7494 |
updatePreviewWindow(false) |
| 7495 |
} else { |
| 7496 |
req(reqQuit) |
| 7497 |
} |
| 7498 |
case actSelect: |
| 7499 |
current := t.currentItem() |
| 7500 |
if t.multi > 0 && current != nil && t.selectItemChanged(current) { |
| 7501 |
req(reqList, reqInfo) |
| 7502 |
} |
| 7503 |
case actDeselect: |
| 7504 |
current := t.currentItem() |
| 7505 |
if t.multi > 0 && current != nil && t.deselectItemChanged(current) { |
| 7506 |
req(reqList, reqInfo) |
| 7507 |
} |
| 7508 |
case actToggle: |
| 7509 |
if t.multi > 0 && t.merger.Length() > 0 && toggle() { |
| 7510 |
req(reqList) |
| 7511 |
} |
| 7512 |
case actToggleAll: |
| 7513 |
if t.multi > 0 { |
| 7514 |
prevIndexes := make(map[int]struct{}) |
| 7515 |
for i := 0; i < t.resultMerger.Length() && len(t.selected) > 0; i++ { |
| 7516 |
item := t.resultMerger.Get(i).item |
| 7517 |
if _, found := t.selected[item.Index()]; found { |
| 7518 |
prevIndexes[i] = struct{}{} |
| 7519 |
t.deselectItem(item) |
| 7520 |
} |
| 7521 |
} |
| 7522 |
|
| 7523 |
for i := 0; i < t.resultMerger.Length(); i++ { |
| 7524 |
if _, found := prevIndexes[i]; !found { |
| 7525 |
item := t.resultMerger.Get(i).item |
| 7526 |
if !t.selectItem(item) { |
| 7527 |
break |
| 7528 |
} |
| 7529 |
} |
| 7530 |
} |
| 7531 |
req(reqList, reqInfo) |
| 7532 |
} |
| 7533 |
case actToggleIn: |
| 7534 |
if t.layout != layoutDefault { |
| 7535 |
return doAction(&action{t: actToggleUp}) |
| 7536 |
} |
| 7537 |
return doAction(&action{t: actToggleDown}) |
| 7538 |
case actToggleOut: |
| 7539 |
if t.layout != layoutDefault { |
| 7540 |
return doAction(&action{t: actToggleDown}) |
| 7541 |
} |
| 7542 |
return doAction(&action{t: actToggleUp}) |
| 7543 |
case actToggleDown: |
| 7544 |
if t.multi > 0 && t.merger.Length() > 0 && toggle() { |
| 7545 |
t.vmove(-1, true) |
| 7546 |
req(reqList) |
| 7547 |
} |
| 7548 |
case actToggleUp: |
| 7549 |
if t.multi > 0 && t.merger.Length() > 0 && toggle() { |
| 7550 |
t.vmove(1, true) |
| 7551 |
req(reqList) |
| 7552 |
} |
| 7553 |
case actDown, actDownMatch, actUp, actUpMatch: |
| 7554 |
dir := -1 |
| 7555 |
if a.t == actUp || a.t == actUpMatch { |
| 7556 |
dir = 1 |
| 7557 |
} |
| 7558 |
if t.raw && (a.t == actDownMatch || a.t == actUpMatch) { |
| 7559 |
if t.resultMerger.Length() > 0 { |
| 7560 |
prevCy := t.cy |
| 7561 |
for t.vmove(dir, true) && !t.isCurrentItemMatch() { |
| 7562 |
} |
| 7563 |
if !t.isCurrentItemMatch() { |
| 7564 |
t.vset(prevCy) |
| 7565 |
} |
| 7566 |
} |
| 7567 |
} else { |
| 7568 |
t.vmove(dir, true) |
| 7569 |
} |
| 7570 |
req(reqList) |
| 7571 |
case actToggleRaw, actEnableRaw, actDisableRaw: |
| 7572 |
prevRaw := t.raw |
| 7573 |
newRaw := t.raw |
| 7574 |
switch a.t { |
| 7575 |
case actEnableRaw: |
| 7576 |
newRaw = true |
| 7577 |
case actDisableRaw: |
| 7578 |
newRaw = false |
| 7579 |
case actToggleRaw: |
| 7580 |
newRaw = !t.raw |
| 7581 |
} |
| 7582 |
if prevRaw == newRaw { |
| 7583 |
break |
| 7584 |
} |
| 7585 |
prevPos := t.cy - t.offset |
| 7586 |
prevIndex := t.currentIndex() |
| 7587 |
if newRaw { |
| 7588 |
// Build matchMap if not available |
| 7589 |
if len(t.matchMap) == 0 { |
| 7590 |
t.matchMap = t.resultMerger.ToMap() |
| 7591 |
} |
| 7592 |
t.merger = t.passMerger |
| 7593 |
} else { |
| 7594 |
// Find the closest matching item |
| 7595 |
if !t.isCurrentItemMatch() && t.resultMerger.Length() > 1 { |
| 7596 |
distance := 0 |
| 7597 |
Loop: |
| 7598 |
for { |
| 7599 |
distance++ |
| 7600 |
checks := 0 |
| 7601 |
for _, cy := range []int{t.cy + distance, t.cy - distance} { |
| 7602 |
if cy >= 0 && cy < t.merger.Length() { |
| 7603 |
checks++ |
| 7604 |
item := t.merger.Get(cy).item |
| 7605 |
if t.isItemMatch(item) { |
| 7606 |
prevIndex = item.Index() |
| 7607 |
break Loop |
| 7608 |
} |
| 7609 |
} |
| 7610 |
} |
| 7611 |
if checks == 0 { |
| 7612 |
break |
| 7613 |
} |
| 7614 |
} |
| 7615 |
} |
| 7616 |
|
| 7617 |
t.merger = t.resultMerger |
| 7618 |
|
| 7619 |
// Need to remove non-matching items from the selection |
| 7620 |
if t.multi > 0 && len(t.selected) > 0 { |
| 7621 |
t.filterSelected() |
| 7622 |
req(reqInfo) |
| 7623 |
} |
| 7624 |
} |
| 7625 |
t.raw = newRaw |
| 7626 |
|
| 7627 |
// Try to retain position |
| 7628 |
if prevIndex != minItem.Index() { |
| 7629 |
t.cy = max(0, t.merger.FindIndex(prevIndex)) |
| 7630 |
t.offset = t.cy - prevPos |
| 7631 |
} |
| 7632 |
|
| 7633 |
// List needs to be rerendered |
| 7634 |
t.forceRerenderList() |
| 7635 |
req(reqList) |
| 7636 |
case actAccept: |
| 7637 |
req(reqClose) |
| 7638 |
case actAcceptNonEmpty: |
| 7639 |
if len(t.selected) > 0 || t.merger.Length() > 0 || !t.reading && t.count == 0 { |
| 7640 |
req(reqClose) |
| 7641 |
} |
| 7642 |
case actAcceptOrPrintQuery: |
| 7643 |
if len(t.selected) > 0 || t.merger.Length() > 0 { |
| 7644 |
req(reqClose) |
| 7645 |
} else { |
| 7646 |
req(reqPrintQuery) |
| 7647 |
} |
| 7648 |
case actClearScreen: |
| 7649 |
req(reqFullRedraw) |
| 7650 |
case actClearQuery: |
| 7651 |
t.input = []rune{} |
| 7652 |
t.cx = 0 |
| 7653 |
case actClearSelection: |
| 7654 |
if t.multi > 0 { |
| 7655 |
t.selected = make(map[int32]selectedItem) |
| 7656 |
t.version++ |
| 7657 |
req(reqList, reqInfo) |
| 7658 |
} |
| 7659 |
case actFirst, actBest: |
| 7660 |
if t.raw && a.t == actBest { |
| 7661 |
if t.resultMerger.Length() > 0 { |
| 7662 |
t.vset(t.merger.FindIndex(t.resultMerger.Get(0).item.Index())) |
| 7663 |
} |
| 7664 |
} else { |
| 7665 |
t.vset(0) |
| 7666 |
} |
| 7667 |
t.constrain() |
| 7668 |
req(reqList) |
| 7669 |
case actLast: |
| 7670 |
t.vset(t.merger.Length() - 1) |
| 7671 |
t.constrain() |
| 7672 |
req(reqList) |
| 7673 |
case actPosition: |
| 7674 |
if n, e := strconv.Atoi(a.a); e == nil { |
| 7675 |
if n > 0 { |
| 7676 |
n-- |
| 7677 |
} else if n < 0 { |
| 7678 |
n += t.merger.Length() |
| 7679 |
} |
| 7680 |
t.vset(n) |
| 7681 |
t.constrain() |
| 7682 |
req(reqList) |
| 7683 |
} |
| 7684 |
case actPut: |
| 7685 |
str := []rune(a.a) |
| 7686 |
suffix := copySlice(t.input[t.cx:]) |
| 7687 |
t.input = append(append(t.input[:t.cx], str...), suffix...) |
| 7688 |
t.cx += len(str) |
| 7689 |
case actPrint: |
| 7690 |
t.printQueue = append(t.printQueue, a.a) |
| 7691 |
case actUnixLineDiscard: |
| 7692 |
beof = len(t.input) == 0 |
| 7693 |
if t.cx > 0 { |
| 7694 |
t.yanked = copySlice(t.input[:t.cx]) |
| 7695 |
t.input = t.input[t.cx:] |
| 7696 |
t.cx = 0 |
| 7697 |
} |
| 7698 |
case actUnixWordRubout: |
| 7699 |
beof = len(t.input) == 0 |
| 7700 |
if t.cx > 0 { |
| 7701 |
t.rubout("\\s\\S") |
| 7702 |
} |
| 7703 |
case actBackwardKillWord: |
| 7704 |
beof = len(t.input) == 0 |
| 7705 |
if t.cx > 0 { |
| 7706 |
t.rubout(t.wordRubout) |
| 7707 |
} |
| 7708 |
case actBackwardKillSubWord: |
| 7709 |
beof = len(t.input) == 0 |
| 7710 |
if t.cx > 0 { |
| 7711 |
t.rubout(t.subWordRubout) |
| 7712 |
} |
| 7713 |
case actYank: |
| 7714 |
suffix := copySlice(t.input[t.cx:]) |
| 7715 |
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...) |
| 7716 |
t.cx += len(t.yanked) |
| 7717 |
case actPageUp, actPageDown, actHalfPageUp, actHalfPageDown: |
| 7718 |
// Calculate the number of lines to move |
| 7719 |
maxItems := t.maxItems() |
| 7720 |
linesToMove := maxItems - 1 |
| 7721 |
if a.t == actHalfPageUp || a.t == actHalfPageDown { |
| 7722 |
linesToMove = maxItems / 2 |
| 7723 |
} |
| 7724 |
// Move at least one line even in a very short window |
| 7725 |
linesToMove = max(1, linesToMove) |
| 7726 |
|
| 7727 |
// Determine the direction of the movement |
| 7728 |
direction := -1 |
| 7729 |
if a.t == actPageUp || a.t == actHalfPageUp { |
| 7730 |
direction = 1 |
| 7731 |
} |
| 7732 |
|
| 7733 |
// In non-default layout, items are listed from top to bottom |
| 7734 |
if t.layout != layoutDefault { |
| 7735 |
direction *= -1 |
| 7736 |
} |
| 7737 |
|
| 7738 |
// We can simply add the number of lines to the current position in |
| 7739 |
// single-line mode |
| 7740 |
if !t.canSpanMultiLines() { |
| 7741 |
t.vset(t.cy + direction*linesToMove) |
| 7742 |
req(reqList) |
| 7743 |
break |
| 7744 |
} |
| 7745 |
|
| 7746 |
// But in multi-line mode, we need to carefully limit the amount of |
| 7747 |
// vertical movement so that items are not skipped. In order to do |
| 7748 |
// this, we calculate the minimum or maximum offset based on the |
| 7749 |
// direction of the movement and the number of lines of the items |
| 7750 |
// around the current scroll offset. |
| 7751 |
var minOffset, maxOffset, lineSum int |
| 7752 |
if direction > 0 { |
| 7753 |
maxOffset = t.offset |
| 7754 |
for ; maxOffset < t.merger.Length(); maxOffset++ { |
| 7755 |
itemLines, _ := t.numItemLines(t.merger.Get(maxOffset).item, maxItems) |
| 7756 |
lineSum += itemLines |
| 7757 |
if lineSum >= maxItems { |
| 7758 |
break |
| 7759 |
} |
| 7760 |
} |
| 7761 |
} else { |
| 7762 |
minOffset = t.offset |
| 7763 |
for ; minOffset >= 0 && minOffset < t.merger.Length(); minOffset-- { |
| 7764 |
itemLines, _ := t.numItemLines(t.merger.Get(minOffset).item, maxItems) |
| 7765 |
lineSum += itemLines |
| 7766 |
if lineSum >= maxItems { |
| 7767 |
if lineSum > maxItems { |
| 7768 |
minOffset++ |
| 7769 |
} |
| 7770 |
break |
| 7771 |
} |
| 7772 |
} |
| 7773 |
} |
| 7774 |
|
| 7775 |
for i := 0; i < linesToMove; i++ { |
| 7776 |
cy, offset := t.cy, t.offset |
| 7777 |
t.vset(cy + direction) |
| 7778 |
t.constrain() |
| 7779 |
if cy == t.cy { |
| 7780 |
break |
| 7781 |
} |
| 7782 |
if i > 0 && (direction > 0 && t.offset > maxOffset || |
| 7783 |
direction < 0 && t.offset < minOffset) { |
| 7784 |
t.cy, t.offset = cy, offset |
| 7785 |
break |
| 7786 |
} |
| 7787 |
} |
| 7788 |
req(reqList) |
| 7789 |
case actOffsetUp, actOffsetDown: |
| 7790 |
diff := 1 |
| 7791 |
if a.t == actOffsetDown { |
| 7792 |
diff = -1 |
| 7793 |
} |
| 7794 |
if t.layout != layoutDefault { |
| 7795 |
diff *= -1 |
| 7796 |
} |
| 7797 |
t.offset += diff |
| 7798 |
before := t.offset |
| 7799 |
t.constrain() |
| 7800 |
if before != t.offset { |
| 7801 |
t.offset = before |
| 7802 |
if t.layout != layoutDefault { |
| 7803 |
diff *= -1 |
| 7804 |
} |
| 7805 |
t.vmove(diff, false) |
| 7806 |
} |
| 7807 |
req(reqList) |
| 7808 |
case actOffsetMiddle: |
| 7809 |
soff := t.scrollOff |
| 7810 |
t.scrollOff = t.window.Height() |
| 7811 |
t.constrain() |
| 7812 |
t.scrollOff = soff |
| 7813 |
req(reqList) |
| 7814 |
case actJump: |
| 7815 |
t.jumping = jumpEnabled |
| 7816 |
req(reqJump) |
| 7817 |
case actJumpAccept: |
| 7818 |
t.jumping = jumpAcceptEnabled |
| 7819 |
req(reqJump) |
| 7820 |
case actBackwardWord: |
| 7821 |
t.cx = findLastMatch(t.wordRubout, string(t.input[:t.cx])) + 1 |
| 7822 |
case actForwardWord: |
| 7823 |
t.cx += findFirstMatch(t.wordNext, string(t.input[t.cx:])) + 1 |
| 7824 |
case actBackwardSubWord: |
| 7825 |
t.cx = findLastMatch(t.subWordRubout, string(t.input[:t.cx])) + 1 |
| 7826 |
case actForwardSubWord: |
| 7827 |
t.cx += findFirstMatch(t.subWordNext, string(t.input[t.cx:])) + 1 |
| 7828 |
case actKillWord: |
| 7829 |
ncx := t.cx + |
| 7830 |
findFirstMatch(t.wordNext, string(t.input[t.cx:])) + 1 |
| 7831 |
if ncx > t.cx { |
| 7832 |
t.yanked = copySlice(t.input[t.cx:ncx]) |
| 7833 |
t.input = append(t.input[:t.cx], t.input[ncx:]...) |
| 7834 |
} |
| 7835 |
case actKillSubWord: |
| 7836 |
ncx := t.cx + |
| 7837 |
findFirstMatch(t.subWordNext, string(t.input[t.cx:])) + 1 |
| 7838 |
if ncx > t.cx { |
| 7839 |
t.yanked = copySlice(t.input[t.cx:ncx]) |
| 7840 |
t.input = append(t.input[:t.cx], t.input[ncx:]...) |
| 7841 |
} |
| 7842 |
case actKillLine: |
| 7843 |
if t.cx < len(t.input) { |
| 7844 |
t.yanked = copySlice(t.input[t.cx:]) |
| 7845 |
t.input = t.input[:t.cx] |
| 7846 |
} |
| 7847 |
case actChar: |
| 7848 |
prefix := copySlice(t.input[:t.cx]) |
| 7849 |
t.input = append(append(prefix, event.Char), t.input[t.cx:]...) |
| 7850 |
t.cx++ |
| 7851 |
case actPrevHistory: |
| 7852 |
if t.history != nil { |
| 7853 |
t.history.override(string(t.input)) |
| 7854 |
t.input = trimQuery(t.history.previous()) |
| 7855 |
t.cx = len(t.input) |
| 7856 |
} |
| 7857 |
case actNextHistory: |
| 7858 |
if t.history != nil { |
| 7859 |
t.history.override(string(t.input)) |
| 7860 |
t.input = trimQuery(t.history.next()) |
| 7861 |
t.cx = len(t.input) |
| 7862 |
} |
| 7863 |
case actToggleSearch: |
| 7864 |
t.paused = !t.paused |
| 7865 |
changed = !t.paused |
| 7866 |
req(reqPrompt) |
| 7867 |
case actToggleTrack: |
| 7868 |
switch t.track { |
| 7869 |
case trackEnabled: |
| 7870 |
t.track = trackDisabled |
| 7871 |
case trackDisabled: |
| 7872 |
t.track = trackEnabled |
| 7873 |
} |
| 7874 |
t.unblockTrack() |
| 7875 |
req(reqPrompt, reqInfo) |
| 7876 |
case actToggleTrackCurrent: |
| 7877 |
if t.track.Current() { |
| 7878 |
t.track = trackDisabled |
| 7879 |
} else if t.track.Disabled() { |
| 7880 |
t.track = trackCurrent(t.currentIndex()) |
| 7881 |
} |
| 7882 |
t.unblockTrack() |
| 7883 |
req(reqPrompt, reqInfo) |
| 7884 |
case actShowHeader: |
| 7885 |
t.headerVisible = true |
| 7886 |
req(reqList, reqInfo, reqPrompt, reqHeader) |
| 7887 |
case actHideHeader: |
| 7888 |
t.headerVisible = false |
| 7889 |
req(reqList, reqInfo, reqPrompt, reqHeader) |
| 7890 |
case actToggleHeader: |
| 7891 |
t.headerVisible = !t.headerVisible |
| 7892 |
req(reqList, reqInfo, reqPrompt, reqHeader) |
| 7893 |
case actToggleWrap, actToggleWrapWord: |
| 7894 |
if a.t == actToggleWrapWord { |
| 7895 |
t.wrapWord = !t.wrapWord |
| 7896 |
t.wrap = t.wrapWord |
| 7897 |
} else { |
| 7898 |
t.wrap = !t.wrap |
| 7899 |
if !t.wrap { |
| 7900 |
t.wrapWord = false |
| 7901 |
} |
| 7902 |
} |
| 7903 |
t.clearNumLinesCache() |
| 7904 |
req(reqList, reqHeader) |
| 7905 |
case actToggleMultiLine: |
| 7906 |
t.multiLine = !t.multiLine |
| 7907 |
t.clearNumLinesCache() |
| 7908 |
req(reqList) |
| 7909 |
case actToggleHscroll: |
| 7910 |
// Force re-rendering of the list |
| 7911 |
t.forceRerenderList() |
| 7912 |
t.hscroll = !t.hscroll |
| 7913 |
req(reqList) |
| 7914 |
case actToggleInput, actShowInput, actHideInput: |
| 7915 |
switch a.t { |
| 7916 |
case actToggleInput: |
| 7917 |
t.inputless = !t.inputless |
| 7918 |
case actShowInput: |
| 7919 |
if !t.inputless { |
| 7920 |
break Action |
| 7921 |
} |
| 7922 |
t.inputless = false |
| 7923 |
case actHideInput: |
| 7924 |
if t.inputless { |
| 7925 |
break Action |
| 7926 |
} |
| 7927 |
t.inputless = true |
| 7928 |
} |
| 7929 |
t.forceRerenderList() |
| 7930 |
if t.inputless { |
| 7931 |
t.tui.HideCursor() |
| 7932 |
} else { |
| 7933 |
t.tui.ShowCursor() |
| 7934 |
} |
| 7935 |
req(reqList, reqInfo, reqPrompt, reqHeader) |
| 7936 |
case actTrackCurrent: |
| 7937 |
// Global tracking has higher priority |
| 7938 |
if !t.track.Global() { |
| 7939 |
t.track = trackCurrent(t.currentIndex()) |
| 7940 |
} |
| 7941 |
req(reqInfo) |
| 7942 |
case actUntrackCurrent: |
| 7943 |
if t.track.Current() { |
| 7944 |
t.track = trackDisabled |
| 7945 |
} |
| 7946 |
t.unblockTrack() |
| 7947 |
req(reqPrompt, reqInfo) |
| 7948 |
case actSearch: |
| 7949 |
override := []rune(a.a) |
| 7950 |
t.inputOverride = &override |
| 7951 |
changed = true |
| 7952 |
case actTransformSearch, actBgTransformSearch: |
| 7953 |
capture(true, func(query string) { |
| 7954 |
override := []rune(query) |
| 7955 |
t.inputOverride = &override |
| 7956 |
changed = true |
| 7957 |
}) |
| 7958 |
case actEnableSearch: |
| 7959 |
t.paused = false |
| 7960 |
changed = true |
| 7961 |
req(reqPrompt) |
| 7962 |
case actDisableSearch: |
| 7963 |
t.paused = true |
| 7964 |
req(reqPrompt) |
| 7965 |
case actTrigger: |
| 7966 |
if _, chords, err := parseKeyChords(a.a, ""); err == nil { |
| 7967 |
blockedBefore := t.wait.blocked |
| 7968 |
for ci, chord := range chords { |
| 7969 |
if _, prs := triggering[chord]; prs { |
| 7970 |
// Avoid recursive triggering |
| 7971 |
continue |
| 7972 |
} |
| 7973 |
if acts, prs := t.keymap[chord]; prs { |
| 7974 |
triggering[chord] = struct{}{} |
| 7975 |
doActions(acts) |
| 7976 |
delete(triggering, chord) |
| 7977 |
} |
| 7978 |
// If this chord armed the wait, defer the remaining chords |
| 7979 |
if !blockedBefore && t.wait.blocked { |
| 7980 |
for _, rest := range chords[ci+1:] { |
| 7981 |
if _, prs := triggering[rest]; prs { |
| 7982 |
// Avoid recursive triggering |
| 7983 |
continue |
| 7984 |
} |
| 7985 |
if acts, prs := t.keymap[rest]; prs { |
| 7986 |
t.wait.pending = append(t.wait.pending, acts...) |
| 7987 |
} |
| 7988 |
} |
| 7989 |
break |
| 7990 |
} |
| 7991 |
} |
| 7992 |
} |
| 7993 |
case actSigStop: |
| 7994 |
p, err := os.FindProcess(os.Getpid()) |
| 7995 |
if err == nil { |
| 7996 |
t.tui.Clear() |
| 7997 |
t.tui.Pause(t.fullscreen) |
| 7998 |
notifyStop(p) |
| 7999 |
t.mutex.Unlock() |
| 8000 |
t.reqBox.Set(reqReinit, nil) |
| 8001 |
return false |
| 8002 |
} |
| 8003 |
case actMouse: |
| 8004 |
me := event.MouseEvent |
| 8005 |
mx, my := me.X, me.Y |
| 8006 |
click := !wasDown && me.Down |
| 8007 |
clicked := wasDown && !me.Down && (mx == pmx && my == pmy) |
| 8008 |
wasDown = me.Down |
| 8009 |
if click { |
| 8010 |
pmx, pmy = mx, my |
| 8011 |
} |
| 8012 |
if !me.Down { |
| 8013 |
barDragging = false |
| 8014 |
pmx, pmy = -1, -1 |
| 8015 |
} |
| 8016 |
if !me.Down || !t.hasPreviewWindow() { |
| 8017 |
pbarDragging = false |
| 8018 |
pborderDragging = -1 |
| 8019 |
previewDraggingPos = -1 |
| 8020 |
} |
| 8021 |
|
| 8022 |
// Scrolling |
| 8023 |
if me.S != 0 { |
| 8024 |
if t.window.Enclose(my, mx) && t.merger.Length() > 0 { |
| 8025 |
evt := tui.ScrollUp |
| 8026 |
if me.Mod() { |
| 8027 |
evt = tui.SScrollUp |
| 8028 |
} |
| 8029 |
if me.S < 0 { |
| 8030 |
evt = tui.ScrollDown |
| 8031 |
if me.Mod() { |
| 8032 |
evt = tui.SScrollDown |
| 8033 |
} |
| 8034 |
} |
| 8035 |
return doActions(actionsFor(evt)) |
| 8036 |
} else if t.hasPreviewWindow() && t.pwindow.Enclose(my, mx) { |
| 8037 |
evt := tui.PreviewScrollUp |
| 8038 |
if me.S < 0 { |
| 8039 |
evt = tui.PreviewScrollDown |
| 8040 |
} |
| 8041 |
return doActions(actionsFor(evt)) |
| 8042 |
} |
| 8043 |
break |
| 8044 |
} |
| 8045 |
|
| 8046 |
// Preview dragging |
| 8047 |
if t.hasPreviewWindow() && me.Down && (previewDraggingPos >= 0 || click && t.pwindow.Enclose(my, mx)) { |
| 8048 |
if previewDraggingPos > 0 { |
| 8049 |
scrollPreviewBy(previewDraggingPos - my) |
| 8050 |
} |
| 8051 |
previewDraggingPos = my |
| 8052 |
break |
| 8053 |
} |
| 8054 |
|
| 8055 |
// Preview scrollbar dragging |
| 8056 |
headerLines := t.activePreviewOpts.headerLines |
| 8057 |
pbarDragging = t.hasPreviewWindow() && me.Down && (pbarDragging || click && my >= t.pwindow.Top()+headerLines && my < t.pwindow.Top()+t.pwindow.Height() && mx == t.pwindow.Left()+t.pwindow.Width()) |
| 8058 |
if pbarDragging { |
| 8059 |
effectiveHeight := t.pwindow.Height() - headerLines |
| 8060 |
numLines := len(t.previewer.lines) - headerLines |
| 8061 |
barLength, _ := getScrollbar(1, numLines, effectiveHeight, min(numLines-effectiveHeight, t.previewer.offset-headerLines)) |
| 8062 |
if barLength > 0 { |
| 8063 |
y := my - t.pwindow.Top() - headerLines - barLength/2 |
| 8064 |
y = util.Constrain(y, 0, effectiveHeight-barLength) |
| 8065 |
// offset = (total - maxItems) * barStart / (maxItems - barLength) |
| 8066 |
t.previewer.offset = headerLines + int(math.Ceil(float64(y)*float64(numLines-effectiveHeight)/float64(effectiveHeight-barLength))) |
| 8067 |
t.previewer.following.Set(t.previewer.offset >= numLines-effectiveHeight) |
| 8068 |
req(reqPreviewRefresh) |
| 8069 |
} |
| 8070 |
break |
| 8071 |
} |
| 8072 |
|
| 8073 |
// Preview border dragging (resizing) |
| 8074 |
if t.hasPreviewWindow() && pborderDragging < 0 && click { |
| 8075 |
switch t.activePreviewOpts.position { |
| 8076 |
case posUp: |
| 8077 |
if t.pborder.Enclose(my, mx) && my == t.pborder.Top()+t.pborder.Height()-1 { |
| 8078 |
pborderDragging = 0 |
| 8079 |
} else if t.listBorderShape.HasTop() && t.pborder.EncloseX(mx) && my == t.wborder.Top() { |
| 8080 |
pborderDragging = 1 |
| 8081 |
} |
| 8082 |
case posDown: |
| 8083 |
if t.pborder.Enclose(my, mx) && my == t.pborder.Top() { |
| 8084 |
pborderDragging = 0 |
| 8085 |
} else if t.listBorderShape.HasBottom() && t.pborder.EncloseX(mx) && my == t.wborder.Top()+t.wborder.Height()-1 { |
| 8086 |
pborderDragging = 1 |
| 8087 |
} |
| 8088 |
case posLeft: |
| 8089 |
if t.pborder.Enclose(my, mx) && mx == t.pborder.Left()+t.pborder.Width()-1 { |
| 8090 |
pborderDragging = 0 |
| 8091 |
} else if t.listBorderShape.HasLeft() && t.pborder.EncloseY(my) && mx == t.wborder.Left() { |
| 8092 |
pborderDragging = 1 |
| 8093 |
} |
| 8094 |
case posRight: |
| 8095 |
if t.pborder.Enclose(my, mx) && mx == t.pborder.Left() { |
| 8096 |
pborderDragging = 0 |
| 8097 |
} else if t.listBorderShape.HasRight() && t.pborder.EncloseY(my) && mx == t.wborder.Left()+t.wborder.Width()-1 { |
| 8098 |
pborderDragging = 1 |
| 8099 |
} |
| 8100 |
case posNext: |
| 8101 |
if t.layout == layoutReverse { |
| 8102 |
if t.pborder.Enclose(my, mx) && my == t.pborder.Top()+t.pborder.Height()-1 { |
| 8103 |
pborderDragging = 0 |
| 8104 |
} else if t.listBorderShape.HasTop() && t.pborder.EncloseX(mx) && my == t.wborder.Top() { |
| 8105 |
pborderDragging = 1 |
| 8106 |
} |
| 8107 |
} else { |
| 8108 |
if t.pborder.Enclose(my, mx) && my == t.pborder.Top() { |
| 8109 |
pborderDragging = 0 |
| 8110 |
} else if t.listBorderShape.HasBottom() && t.pborder.EncloseX(mx) && my == t.wborder.Top()+t.wborder.Height()-1 { |
| 8111 |
pborderDragging = 1 |
| 8112 |
} |
| 8113 |
} |
| 8114 |
} |
| 8115 |
} |
| 8116 |
|
| 8117 |
if t.hasPreviewWindow() && pborderDragging >= 0 { |
| 8118 |
var newSize int |
| 8119 |
var prevSize int |
| 8120 |
switch t.activePreviewOpts.position { |
| 8121 |
case posLeft: |
| 8122 |
prevSize = t.pwindow.Width() |
| 8123 |
diff := t.pborder.Width() - prevSize |
| 8124 |
newSize = mx - t.pborder.Left() - diff + 1 |
| 8125 |
case posUp: |
| 8126 |
prevSize = t.pwindow.Height() |
| 8127 |
diff := t.pborder.Height() - prevSize |
| 8128 |
newSize = my - t.pborder.Top() - diff + 1 |
| 8129 |
case posDown: |
| 8130 |
prevSize = t.pwindow.Height() |
| 8131 |
offset := my - t.pborder.Top() |
| 8132 |
newSize = prevSize - offset |
| 8133 |
case posRight: |
| 8134 |
prevSize = t.pwindow.Width() |
| 8135 |
offset := mx - t.pborder.Left() |
| 8136 |
newSize = prevSize - offset |
| 8137 |
case posNext: |
| 8138 |
prevSize = t.pwindow.Height() |
| 8139 |
// In posNext, header/header-lines sections may sit |
| 8140 |
// between preview and list. When the list border is |
| 8141 |
// dragged (pborderDragging == 1), subtract that gap |
| 8142 |
// so the initial click does not jump. |
| 8143 |
headerGap := 0 |
| 8144 |
if pborderDragging == 1 && t.wborder != nil { |
| 8145 |
if t.layout == layoutReverse { |
| 8146 |
headerGap = t.wborder.Top() - (t.pborder.Top() + t.pborder.Height()) |
| 8147 |
} else { |
| 8148 |
headerGap = t.pborder.Top() - (t.wborder.Top() + t.wborder.Height()) |
| 8149 |
} |
| 8150 |
} |
| 8151 |
if t.layout == layoutReverse { |
| 8152 |
diff := t.pborder.Height() - prevSize |
| 8153 |
newSize = my - t.pborder.Top() - diff + 1 - headerGap |
| 8154 |
} else { |
| 8155 |
offset := my - t.pborder.Top() |
| 8156 |
newSize = prevSize - offset - headerGap |
| 8157 |
} |
| 8158 |
} |
| 8159 |
newSize -= pborderDragging |
| 8160 |
if newSize < 1 { |
| 8161 |
newSize = 1 |
| 8162 |
} |
| 8163 |
|
| 8164 |
if prevSize == newSize { |
| 8165 |
break |
| 8166 |
} |
| 8167 |
|
| 8168 |
t.activePreviewOpts.size = sizeSpec{float64(newSize), false} |
| 8169 |
updatePreviewWindow(true) |
| 8170 |
req(reqPreviewRefresh) |
| 8171 |
break |
| 8172 |
} |
| 8173 |
|
| 8174 |
// Inside the input window |
| 8175 |
if t.inputWindow != nil && t.inputWindow.Enclose(my, mx) { |
| 8176 |
mx -= t.inputWindow.Left() |
| 8177 |
my -= t.inputWindow.Top() |
| 8178 |
y := t.inputWindow.Height() - 1 |
| 8179 |
if t.layout == layoutReverse { |
| 8180 |
y = 0 |
| 8181 |
} |
| 8182 |
mxCons := util.Constrain(mx-t.promptLen, 0, len(t.input)) |
| 8183 |
if my == y && mxCons >= 0 { |
| 8184 |
t.cx = mxCons + t.xoffset |
| 8185 |
} |
| 8186 |
break |
| 8187 |
} |
| 8188 |
|
| 8189 |
// Inside the header window |
| 8190 |
if clicked && t.headerVisible && t.headerWindow != nil && t.headerWindow.Enclose(my, mx) { |
| 8191 |
mx -= t.headerWindow.Left() + t.headerIndent(t.headerBorderShape) |
| 8192 |
my -= t.headerWindow.Top() |
| 8193 |
if mx < 0 { |
| 8194 |
break |
| 8195 |
} |
| 8196 |
t.clickHeaderLine = my + 1 |
| 8197 |
if t.layout != layoutReverse && t.headerLinesWindow != nil { |
| 8198 |
t.clickHeaderLine += t.headerLines |
| 8199 |
} |
| 8200 |
t.clickHeaderColumn = mx + 1 |
| 8201 |
return doActions(actionsFor(tui.ClickHeader)) |
| 8202 |
} |
| 8203 |
|
| 8204 |
if clicked && t.headerVisible && t.headerLinesWindow != nil && t.headerLinesWindow.Enclose(my, mx) { |
| 8205 |
_, shape := t.determineHeaderLinesShape() |
| 8206 |
mx -= t.headerLinesWindow.Left() + t.headerIndent(shape) |
| 8207 |
my -= t.headerLinesWindow.Top() |
| 8208 |
if mx < 0 { |
| 8209 |
break |
| 8210 |
} |
| 8211 |
t.clickHeaderLine = my + 1 |
| 8212 |
if t.layout == layoutReverse { |
| 8213 |
t.clickHeaderLine += len(t.header0) |
| 8214 |
} |
| 8215 |
t.clickHeaderColumn = mx + 1 |
| 8216 |
return doActions(actionsFor(tui.ClickHeader)) |
| 8217 |
} |
| 8218 |
|
| 8219 |
// Inside the footer window |
| 8220 |
if clicked && t.footerWindow != nil && t.footerWindow.Enclose(my, mx) { |
| 8221 |
mx -= t.footerWindow.Left() + t.headerIndent(t.footerBorderShape) |
| 8222 |
my -= t.footerWindow.Top() |
| 8223 |
if mx < 0 { |
| 8224 |
break |
| 8225 |
} |
| 8226 |
t.clickFooterLine = my + 1 |
| 8227 |
t.clickFooterColumn = mx + 1 |
| 8228 |
return doActions(actionsFor(tui.ClickFooter)) |
| 8229 |
} |
| 8230 |
|
| 8231 |
// Ignored |
| 8232 |
if !t.window.Enclose(my, mx) && !barDragging { |
| 8233 |
break |
| 8234 |
} |
| 8235 |
|
| 8236 |
// Translate coordinates |
| 8237 |
mx -= t.window.Left() |
| 8238 |
my -= t.window.Top() |
| 8239 |
min := t.promptLines() + t.visibleHeaderLinesInList() |
| 8240 |
h := t.window.Height() |
| 8241 |
switch t.layout { |
| 8242 |
case layoutDefault: |
| 8243 |
my = h - my - 1 |
| 8244 |
case layoutReverseList: |
| 8245 |
if my < h-min { |
| 8246 |
my += min |
| 8247 |
} else { |
| 8248 |
my = h - my - 1 |
| 8249 |
} |
| 8250 |
} |
| 8251 |
|
| 8252 |
// Scrollbar dragging |
| 8253 |
barDragging = me.Down && (barDragging || click && my >= min && mx == t.window.Width()-1) |
| 8254 |
if barDragging { |
| 8255 |
barLength, barStart := t.getScrollbar() |
| 8256 |
if barLength > 0 { |
| 8257 |
maxItems := t.maxItems() |
| 8258 |
if newBarStart := util.Constrain(my-min-barLength/2, 0, maxItems-barLength); newBarStart != barStart { |
| 8259 |
total := t.merger.Length() |
| 8260 |
prevOffset := t.offset |
| 8261 |
// barStart = (maxItems - barLength) * t.offset / (total - maxItems) |
| 8262 |
perLine := t.avgNumLines() |
| 8263 |
t.offset = int(math.Ceil(float64(newBarStart) * float64(total*perLine-maxItems) / float64(maxItems*perLine-barLength))) |
| 8264 |
t.cy = t.offset + t.cy - prevOffset |
| 8265 |
req(reqList) |
| 8266 |
} |
| 8267 |
} |
| 8268 |
break |
| 8269 |
} |
| 8270 |
|
| 8271 |
// There can be empty lines after the list in multi-line mode |
| 8272 |
prevLine := t.prevLines[my] |
| 8273 |
if prevLine.empty { |
| 8274 |
break |
| 8275 |
} |
| 8276 |
|
| 8277 |
// Double-click on an item |
| 8278 |
cy := prevLine.cy |
| 8279 |
if me.Double && mx < t.window.Width()-1 { |
| 8280 |
// Double-click |
| 8281 |
if my >= min { |
| 8282 |
if t.vset(cy) && t.cy < t.merger.Length() { |
| 8283 |
return doActions(actionsFor(tui.DoubleClick)) |
| 8284 |
} |
| 8285 |
} |
| 8286 |
} |
| 8287 |
|
| 8288 |
if me.Down { |
| 8289 |
mxCons := util.Constrain(mx-t.promptLen, 0, len(t.input)) |
| 8290 |
if !t.inputless && t.inputWindow == nil && my == 0 && mxCons >= 0 { |
| 8291 |
// Prompt |
| 8292 |
t.cx = mxCons + t.xoffset |
| 8293 |
} else if my >= min { |
| 8294 |
t.vset(cy) |
| 8295 |
req(reqList) |
| 8296 |
evt := tui.RightClick |
| 8297 |
if me.Mod() { |
| 8298 |
evt = tui.SRightClick |
| 8299 |
} |
| 8300 |
if me.Left { |
| 8301 |
evt = tui.LeftClick |
| 8302 |
if me.Mod() { |
| 8303 |
evt = tui.SLeftClick |
| 8304 |
} |
| 8305 |
} |
| 8306 |
return doActions(actionsFor(evt)) |
| 8307 |
} |
| 8308 |
} |
| 8309 |
if clicked && t.headerVisible && t.headerWindow == nil { |
| 8310 |
// Header |
| 8311 |
numLines := t.visibleHeaderLinesInList() |
| 8312 |
lineOffset := 0 |
| 8313 |
if !t.inputless && t.inputWindow == nil && !t.headerFirst { |
| 8314 |
// offset for info line |
| 8315 |
if t.noSeparatorLine() { |
| 8316 |
lineOffset = 1 |
| 8317 |
} else { |
| 8318 |
lineOffset = 2 |
| 8319 |
} |
| 8320 |
} |
| 8321 |
my -= lineOffset |
| 8322 |
mx -= t.pointerLen + t.markerLen |
| 8323 |
if my >= 0 && my < numLines && mx >= 0 { |
| 8324 |
if t.layout == layoutReverse { |
| 8325 |
t.clickHeaderLine = my + 1 |
| 8326 |
} else { |
| 8327 |
t.clickHeaderLine = numLines - my |
| 8328 |
} |
| 8329 |
t.clickHeaderColumn = mx + 1 |
| 8330 |
return doActions(actionsFor(tui.ClickHeader)) |
| 8331 |
} |
| 8332 |
} |
| 8333 |
case actReload, actReloadSync: |
| 8334 |
t.failed = nil |
| 8335 |
|
| 8336 |
valid, list := t.buildPlusList(a.a, false) |
| 8337 |
if !valid { |
| 8338 |
// We run the command even when there's no match |
| 8339 |
// 1. If the template doesn't have any slots |
| 8340 |
// 2. If the template has {q} |
| 8341 |
slot, _, _, forceUpdate := hasPreviewFlags(a.a) |
| 8342 |
valid = !slot || forceUpdate |
| 8343 |
} |
| 8344 |
if valid { |
| 8345 |
command, tempFiles := t.replacePlaceholder(a.a, false, string(t.input), list) |
| 8346 |
newCommand = &commandSpec{command, tempFiles} |
| 8347 |
reloadSync = a.t == actReloadSync |
| 8348 |
t.reading = true |
| 8349 |
|
| 8350 |
if len(t.idNth) > 0 { |
| 8351 |
t.trackSync = reloadSync |
| 8352 |
} |
| 8353 |
// Capture tracking key before reload |
| 8354 |
if !t.track.Disabled() && len(t.idNth) > 0 { |
| 8355 |
if item := t.currentItem(); item != nil { |
| 8356 |
t.trackKey = t.trackKeyFor(item, t.idNth) |
| 8357 |
t.trackKeyCache = make(map[int32]bool) |
| 8358 |
t.trackBlocked = true |
| 8359 |
if !t.inputless { |
| 8360 |
t.tui.HideCursor() |
| 8361 |
} |
| 8362 |
req(reqPrompt, reqInfo) |
| 8363 |
} |
| 8364 |
} |
| 8365 |
} |
| 8366 |
case actUnbind: |
| 8367 |
if keys, _, err := parseKeyChords(a.a, "PANIC"); err == nil { |
| 8368 |
for key := range keys { |
| 8369 |
delete(t.keymap, key) |
| 8370 |
} |
| 8371 |
} |
| 8372 |
case actRebind: |
| 8373 |
if keys, _, err := parseKeyChords(a.a, "PANIC"); err == nil { |
| 8374 |
for key := range keys { |
| 8375 |
if originalAction, found := t.keymapOrg[key]; found { |
| 8376 |
t.keymap[key] = originalAction |
| 8377 |
} |
| 8378 |
} |
| 8379 |
} |
| 8380 |
case actToggleBind: |
| 8381 |
if keys, _, err := parseKeyChords(a.a, "PANIC"); err == nil { |
| 8382 |
for key := range keys { |
| 8383 |
if _, bound := t.keymap[key]; bound { |
| 8384 |
delete(t.keymap, key) |
| 8385 |
} else if originalAction, found := t.keymapOrg[key]; found { |
| 8386 |
t.keymap[key] = originalAction |
| 8387 |
} |
| 8388 |
} |
| 8389 |
} |
| 8390 |
case actChangeGhost, actTransformGhost, actBgTransformGhost: |
| 8391 |
capture(true, func(ghost string) { |
| 8392 |
t.ghost = ghost |
| 8393 |
if len(t.input) == 0 { |
| 8394 |
req(reqPrompt) |
| 8395 |
} |
| 8396 |
}) |
| 8397 |
case actChangePointer, actTransformPointer, actBgTransformPointer: |
| 8398 |
capture(true, func(pointer string) { |
| 8399 |
length := uniseg.StringWidth(pointer) |
| 8400 |
if length <= 2 { |
| 8401 |
if length != t.pointerLen { |
| 8402 |
t.forceRerenderList() |
| 8403 |
} |
| 8404 |
t.pointer = pointer |
| 8405 |
t.pointerLen = length |
| 8406 |
t.pointerEmpty = strings.Repeat(" ", t.pointerLen) |
| 8407 |
req(reqList) |
| 8408 |
} |
| 8409 |
}) |
| 8410 |
case actChangePreview: |
| 8411 |
if t.previewOpts.command != a.a { |
| 8412 |
t.previewOpts.command = a.a |
| 8413 |
updatePreviewWindow(false) |
| 8414 |
refreshPreview(t.previewOpts.command) |
| 8415 |
} |
| 8416 |
case actChangePreviewWindow: |
| 8417 |
// NOTE: We intentionally use "previewOpts" instead of "activePreviewOpts" here |
| 8418 |
currentPreviewOpts := t.previewOpts |
| 8419 |
wasNoSeparatorLine := t.noSeparatorLine() |
| 8420 |
wasSeparatorLength := t.separatorLength() |
| 8421 |
|
| 8422 |
// Reset preview options and apply the additional options |
| 8423 |
t.previewOpts = t.initialPreviewOpts |
| 8424 |
t.previewOpts.command = currentPreviewOpts.command |
| 8425 |
|
| 8426 |
// Carry over toggle-driven state so toggle-preview-wrap survives |
| 8427 |
// a change-preview-window. Tokens below can still override. |
| 8428 |
t.previewOpts.wrap = currentPreviewOpts.wrap |
| 8429 |
t.previewOpts.wrapWord = currentPreviewOpts.wrapWord |
| 8430 |
|
| 8431 |
// Split window options |
| 8432 |
tokens := strings.Split(a.a, "|") |
| 8433 |
if len(tokens[0]) > 0 && t.initialPreviewOpts.hidden { |
| 8434 |
t.previewOpts.hidden = false |
| 8435 |
} |
| 8436 |
parsePreviewWindow(&t.previewOpts, tokens[0]) |
| 8437 |
if len(tokens) > 1 { |
| 8438 |
a.a = strings.Join(append(tokens[1:], tokens[0]), "|") |
| 8439 |
} |
| 8440 |
|
| 8441 |
// Do not drop a preview window forced by the preview(...) action |
| 8442 |
keepForcedPreview := t.hasPreviewWindow() && !t.activePreviewOpts.hidden |
| 8443 |
|
| 8444 |
// The default separator is decided from the whole threshold |
| 8445 |
// chain (separatedByBorder), which compare does not fully |
| 8446 |
// inspect, so it can change even when compare finds no |
| 8447 |
// layout difference |
| 8448 |
checkSeparator := func() { |
| 8449 |
if t.noSeparatorLine() != wasNoSeparatorLine { |
| 8450 |
// Number of lines changed; relayout |
| 8451 |
updatePreviewWindow(keepForcedPreview) |
| 8452 |
req(reqPreviewRefresh) |
| 8453 |
} else if t.separatorLength() != wasSeparatorLength { |
| 8454 |
// Only the content of the info line changed |
| 8455 |
req(reqInfo) |
| 8456 |
} |
| 8457 |
} |
| 8458 |
|
| 8459 |
// Full redraw |
| 8460 |
switch currentPreviewOpts.compare(t.activePreviewOpts, &t.previewOpts) { |
| 8461 |
case previewOptsSame: |
| 8462 |
checkSeparator() |
| 8463 |
case previewOptsDifferentLayout: |
| 8464 |
// Preview command can be running in the background if the size of |
| 8465 |
// the preview window is 0 but not 'hidden' |
| 8466 |
wasHidden := currentPreviewOpts.hidden |
| 8467 |
|
| 8468 |
// FIXME: One-time preview window can't reappear once hidden |
| 8469 |
// fzf --bind space:preview:ls --bind 'enter:change-preview-window:down|left|up|hidden|' |
| 8470 |
updatePreviewWindow(keepForcedPreview) |
| 8471 |
if wasHidden && t.hasPreviewWindow() { |
| 8472 |
// Restart |
| 8473 |
refreshPreview(t.previewOpts.command) |
| 8474 |
} else if t.activePreviewOpts.hidden { |
| 8475 |
// Cancel |
| 8476 |
t.cancelPreview() |
| 8477 |
} else { |
| 8478 |
// Refresh |
| 8479 |
req(reqPreviewRefresh) |
| 8480 |
} |
| 8481 |
case previewOptsDifferentContentLayout: |
| 8482 |
t.previewed.version = 0 |
| 8483 |
req(reqPreviewRefresh) |
| 8484 |
checkSeparator() |
| 8485 |
} |
| 8486 |
|
| 8487 |
// Adjust scroll offset |
| 8488 |
if t.hasPreviewWindow() && currentPreviewOpts.scroll != t.activePreviewOpts.scroll { |
| 8489 |
scrollPreviewTo(t.evaluateScrollOffset()) |
| 8490 |
} |
| 8491 |
|
| 8492 |
// Resume following |
| 8493 |
t.previewer.following.Force(t.previewOpts.follow) |
| 8494 |
case actNextSelected, actPrevSelected: |
| 8495 |
if len(t.selected) > 0 { |
| 8496 |
total := t.merger.Length() |
| 8497 |
for i := 1; i < total; i++ { |
| 8498 |
y := (t.cy + i) % total |
| 8499 |
if t.layout == layoutDefault && a.t == actNextSelected || |
| 8500 |
t.layout != layoutDefault && a.t == actPrevSelected { |
| 8501 |
y = (t.cy - i + total) % total |
| 8502 |
} |
| 8503 |
if _, found := t.selected[t.merger.Get(y).item.Index()]; found { |
| 8504 |
t.vset(y) |
| 8505 |
req(reqList) |
| 8506 |
break |
| 8507 |
} |
| 8508 |
} |
| 8509 |
} |
| 8510 |
} |
| 8511 |
|
| 8512 |
if !processExecution(a.t) { |
| 8513 |
t.lastAction = a.t |
| 8514 |
} |
| 8515 |
|
| 8516 |
if t.inputless { |
| 8517 |
// Always just discard the change |
| 8518 |
t.input = currentInput |
| 8519 |
t.cx = len(t.input) |
| 8520 |
beof = false |
| 8521 |
} else if string(t.input) != string(currentInput) { |
| 8522 |
t.inputOverride = nil |
| 8523 |
} |
| 8524 |
return true |
| 8525 |
} |
| 8526 |
|
| 8527 |
// Execute pending actions if wait just unblocked. Capture the jump |
| 8528 |
// state first so that a pending 'jump' action isn't cancelled right |
| 8529 |
// away by the wake-up event below. |
| 8530 |
jumpingBefore := t.jumping |
| 8531 |
if len(t.wait.pending) > 0 && !t.wait.blocked { |
| 8532 |
pending := t.wait.pending |
| 8533 |
t.wait.pending = nil |
| 8534 |
if !doActions(pending) { |
| 8535 |
continue |
| 8536 |
} |
| 8537 |
} |
| 8538 |
|
| 8539 |
if jumpingBefore == jumpDisabled || len(actions) > 0 { |
| 8540 |
// Break out of jump mode if any action is submitted to the server |
| 8541 |
if jumpingBefore != jumpDisabled { |
| 8542 |
t.jumping = jumpDisabled |
| 8543 |
if acts, prs := t.keymap[tui.JumpCancel.AsEvent()]; prs && !doActions(acts) { |
| 8544 |
continue |
| 8545 |
} |
| 8546 |
req(reqList) |
| 8547 |
} |
| 8548 |
if len(actions) == 0 { |
| 8549 |
actions = t.keymap[event.Comparable()] |
| 8550 |
} |
| 8551 |
if len(actions) == 0 && event.Type == tui.Rune { |
| 8552 |
doAction(&action{t: actChar}) |
| 8553 |
} else if !doActions(actions) { |
| 8554 |
continue |
| 8555 |
} |
| 8556 |
if !t.inputless { |
| 8557 |
t.truncateQuery() |
| 8558 |
} |
| 8559 |
queryChanged = queryChanged || t.pasting == nil && string(previousInput) != string(t.input) |
| 8560 |
changed = changed || queryChanged |
| 8561 |
if onChanges, prs := t.keymap[tui.Change.AsEvent()]; queryChanged && prs && !doActions(onChanges) { |
| 8562 |
continue |
| 8563 |
} |
| 8564 |
if onEOFs, prs := t.keymap[tui.BackwardEOF.AsEvent()]; beof && prs && !doActions(onEOFs) { |
| 8565 |
continue |
| 8566 |
} |
| 8567 |
if onMultis, prs := t.keymap[tui.Multi.AsEvent()]; t.version != previousVersion && prs && !doActions(onMultis) { |
| 8568 |
continue |
| 8569 |
} |
| 8570 |
} else { |
| 8571 |
jumpEvent := tui.JumpCancel |
| 8572 |
if event.Type == tui.Rune { |
| 8573 |
if idx := strings.IndexRune(t.jumpLabels, event.Char); idx >= 0 && idx < t.maxItems() && idx < t.merger.Length() { |
| 8574 |
jumpEvent = tui.Jump |
| 8575 |
t.cy = idx + t.offset |
| 8576 |
if t.jumping == jumpAcceptEnabled { |
| 8577 |
req(reqClose) |
| 8578 |
} |
| 8579 |
} |
| 8580 |
} |
| 8581 |
t.jumping = jumpDisabled |
| 8582 |
if acts, prs := t.keymap[jumpEvent.AsEvent()]; prs && !doActions(acts) { |
| 8583 |
continue |
| 8584 |
} |
| 8585 |
req(reqList) |
| 8586 |
} |
| 8587 |
|
| 8588 |
if queryChanged && t.canPreview() && len(t.previewOpts.command) > 0 { |
| 8589 |
_, _, _, forceUpdate := hasPreviewFlags(t.previewOpts.command) |
| 8590 |
if forceUpdate { |
| 8591 |
t.version++ |
| 8592 |
} |
| 8593 |
} |
| 8594 |
|
| 8595 |
if queryChanged || t.cx != previousCx { |
| 8596 |
req(reqPrompt) |
| 8597 |
} |
| 8598 |
|
| 8599 |
reload := changed || newCommand != nil |
| 8600 |
if reload { |
| 8601 |
t.wait.searching = true |
| 8602 |
t.progress = 0 |
| 8603 |
} |
| 8604 |
var reloadRequest *searchRequest |
| 8605 |
if reload { |
| 8606 |
reloadRequest = &searchRequest{sort: t.sort, sync: reloadSync, nth: newNth, withNth: newWithNth, headerLines: newHeaderLines, command: newCommand, environ: t.environ(), changed: changed, denylist: denylist, revision: t.resultMerger.Revision()} |
| 8607 |
} |
| 8608 |
|
| 8609 |
// Dispatch queued background requests |
| 8610 |
t.dispatchAsync() |
| 8611 |
|
| 8612 |
if t.pendingReqList { |
| 8613 |
t.pendingReqList = false |
| 8614 |
req(reqList) |
| 8615 |
} |
| 8616 |
|
| 8617 |
t.mutex.Unlock() // Must be unlocked before touching reqBox |
| 8618 |
|
| 8619 |
if reload { |
| 8620 |
t.eventBox.Set(EvtSearchNew, *reloadRequest) |
| 8621 |
} |
| 8622 |
for _, event := range events { |
| 8623 |
t.reqBox.Set(event, nil) |
| 8624 |
} |
| 8625 |
} |
| 8626 |
return nil |
| 8627 |
} |
| 8628 |
|
| 8629 |
func (t *Terminal) constrain() { |
| 8630 |
// count of items to display allowed by filtering |
| 8631 |
count := t.merger.Length() |
| 8632 |
maxLines := t.maxItems() |
| 8633 |
|
| 8634 |
// May need to try again after adjusting the offset |
| 8635 |
t.offset = util.Constrain(t.offset, 0, count) |
| 8636 |
for range maxLines { |
| 8637 |
numItems := maxLines |
| 8638 |
// How many items can be fit on screen including the current item? |
| 8639 |
if t.canSpanMultiLines() && t.merger.Length() > 0 { |
| 8640 |
numItemsFound := 0 |
| 8641 |
linesSum := 0 |
| 8642 |
|
| 8643 |
add := func(i int) bool { |
| 8644 |
lines, overflow := t.numItemLines(t.merger.Get(i).item, numItems-linesSum) |
| 8645 |
linesSum += lines |
| 8646 |
if linesSum >= numItems { |
| 8647 |
/* |
| 8648 |
# Should show all 3 items |
| 8649 |
printf "file1\0file2\0file3\0" | fzf --height=5 --read0 --bind load:last --reverse |
| 8650 |
|
| 8651 |
# Should not truncate the last item |
| 8652 |
printf "file\n1\0file\n2\0file\n3\0" | fzf --height=5 --read0 --bind load:last --reverse |
| 8653 |
*/ |
| 8654 |
if numItemsFound == 0 || !overflow { |
| 8655 |
numItemsFound++ |
| 8656 |
} |
| 8657 |
return false |
| 8658 |
} |
| 8659 |
numItemsFound++ |
| 8660 |
return true |
| 8661 |
} |
| 8662 |
|
| 8663 |
for i := t.offset; i < t.merger.Length(); i++ { |
| 8664 |
if !add(i) { |
| 8665 |
break |
| 8666 |
} |
| 8667 |
} |
| 8668 |
|
| 8669 |
// We can possibly fit more items "before" the offset on screen |
| 8670 |
if linesSum < numItems { |
| 8671 |
for i := t.offset - 1; i >= 0; i-- { |
| 8672 |
if !add(i) { |
| 8673 |
break |
| 8674 |
} |
| 8675 |
} |
| 8676 |
} |
| 8677 |
|
| 8678 |
numItems = numItemsFound |
| 8679 |
} |
| 8680 |
|
| 8681 |
t.cy = util.Constrain(t.cy, 0, max(0, count-1)) |
| 8682 |
minOffset := max(t.cy-numItems+1, 0) |
| 8683 |
maxOffset := max(min(count-numItems, t.cy), 0) |
| 8684 |
prevOffset := t.offset |
| 8685 |
t.offset = util.Constrain(t.offset, minOffset, maxOffset) |
| 8686 |
if t.scrollOff > 0 { |
| 8687 |
scrollOff := min(maxLines/2, t.scrollOff) |
| 8688 |
newOffset := t.offset |
| 8689 |
// 2-phase adjustment to avoid infinite loop of alternating between moving up and down |
| 8690 |
for phase := range 2 { |
| 8691 |
for { |
| 8692 |
prevOffset := newOffset |
| 8693 |
numItems := t.merger.Length() |
| 8694 |
itemLines := 1 + t.gap |
| 8695 |
if t.canSpanMultiLines() && t.cy < numItems { |
| 8696 |
itemLines, _ = t.numItemLines(t.merger.Get(t.cy).item, maxLines) |
| 8697 |
} |
| 8698 |
linesBefore := t.cy - newOffset |
| 8699 |
if t.canSpanMultiLines() { |
| 8700 |
linesBefore = 0 |
| 8701 |
for i := newOffset; i < t.cy && i < numItems; i++ { |
| 8702 |
lines, _ := t.numItemLines(t.merger.Get(i).item, maxLines-linesBefore-itemLines) |
| 8703 |
linesBefore += lines |
| 8704 |
} |
| 8705 |
} |
| 8706 |
linesAfter := maxLines - (linesBefore + itemLines) |
| 8707 |
|
| 8708 |
// Stuck in the middle, nothing to do |
| 8709 |
if linesBefore < scrollOff && linesAfter < scrollOff { |
| 8710 |
break |
| 8711 |
} |
| 8712 |
|
| 8713 |
if phase == 0 && linesBefore < scrollOff { |
| 8714 |
newOffset = max(minOffset, newOffset-1) |
| 8715 |
} else if phase == 1 && linesAfter < scrollOff { |
| 8716 |
newOffset = min(maxOffset, newOffset+1) |
| 8717 |
} |
| 8718 |
if newOffset == prevOffset { |
| 8719 |
break |
| 8720 |
} |
| 8721 |
} |
| 8722 |
t.offset = newOffset |
| 8723 |
} |
| 8724 |
} |
| 8725 |
if t.offset == prevOffset { |
| 8726 |
break |
| 8727 |
} |
| 8728 |
} |
| 8729 |
} |
| 8730 |
|
| 8731 |
// Returns true if the cursor position is successfully updated |
| 8732 |
func (t *Terminal) vmove(o int, allowCycle bool) bool { |
| 8733 |
if t.layout != layoutDefault { |
| 8734 |
o *= -1 |
| 8735 |
} |
| 8736 |
dest := t.cy + o |
| 8737 |
if t.cycle && allowCycle { |
| 8738 |
max := t.merger.Length() - 1 |
| 8739 |
if dest > max { |
| 8740 |
if t.cy == max { |
| 8741 |
dest = 0 |
| 8742 |
} |
| 8743 |
} else if dest < 0 { |
| 8744 |
if t.cy == 0 { |
| 8745 |
dest = max |
| 8746 |
} |
| 8747 |
} |
| 8748 |
} |
| 8749 |
return t.vset(dest) |
| 8750 |
} |
| 8751 |
|
| 8752 |
func (t *Terminal) vset(o int) bool { |
| 8753 |
t.cy = util.Constrain(o, 0, t.merger.Length()-1) |
| 8754 |
return t.cy == o |
| 8755 |
} |
| 8756 |
|
| 8757 |
// Number of prompt lines in the list window |
| 8758 |
func (t *Terminal) promptLines() int { |
| 8759 |
if t.inputless { |
| 8760 |
return 0 |
| 8761 |
} |
| 8762 |
if t.inputWindow != nil { |
| 8763 |
return 0 |
| 8764 |
} |
| 8765 |
if t.noSeparatorLine() { |
| 8766 |
return 1 |
| 8767 |
} |
| 8768 |
return 2 |
| 8769 |
} |
| 8770 |
|
| 8771 |
// Number of item lines in the list window |
| 8772 |
func (t *Terminal) maxItems() int { |
| 8773 |
maximum := t.window.Height() - t.visibleHeaderLinesInList() - t.promptLines() |
| 8774 |
return max(maximum, 0) |
| 8775 |
} |
| 8776 |
|
| 8777 |
func (t *Terminal) dumpItem(i *Item) StatusItem { |
| 8778 |
if i == nil { |
| 8779 |
return StatusItem{} |
| 8780 |
} |
| 8781 |
item := StatusItem{ |
| 8782 |
Index: int(i.Index()), |
| 8783 |
Text: i.AsString(t.ansi), |
| 8784 |
} |
| 8785 |
if t.resultMerger.pattern != nil { |
| 8786 |
_, _, pos := t.resultMerger.pattern.MatchItem(i, true, t.slab) |
| 8787 |
if pos != nil { |
| 8788 |
sort.Ints(*pos) |
| 8789 |
item.Positions = *pos |
| 8790 |
} |
| 8791 |
} |
| 8792 |
return item |
| 8793 |
} |
| 8794 |
|
| 8795 |
func (t *Terminal) tryLock(timeout time.Duration) bool { |
| 8796 |
sleepDuration := 10 * time.Millisecond |
| 8797 |
|
| 8798 |
for { |
| 8799 |
if t.mutex.TryLock() { |
| 8800 |
return true |
| 8801 |
} |
| 8802 |
|
| 8803 |
timeout -= sleepDuration |
| 8804 |
if timeout <= 0 { |
| 8805 |
break |
| 8806 |
} |
| 8807 |
time.Sleep(sleepDuration) |
| 8808 |
} |
| 8809 |
return false |
| 8810 |
} |
| 8811 |
|
| 8812 |
func (t *Terminal) dumpStatus(params getParams) string { |
| 8813 |
if !t.tryLock(channelTimeout) { |
| 8814 |
return "" |
| 8815 |
} |
| 8816 |
defer t.mutex.Unlock() |
| 8817 |
|
| 8818 |
selectedItems := t.sortSelected() |
| 8819 |
selected := make([]StatusItem, max(0, min(params.limit, len(selectedItems)-params.offset))) |
| 8820 |
for i := range selected { |
| 8821 |
selected[i] = t.dumpItem(selectedItems[i+params.offset].item) |
| 8822 |
} |
| 8823 |
|
| 8824 |
matches := make([]StatusItem, max(0, min(params.limit, t.resultMerger.Length()-params.offset))) |
| 8825 |
for i := range matches { |
| 8826 |
matches[i] = t.dumpItem(t.resultMerger.Get(i + params.offset).item) |
| 8827 |
} |
| 8828 |
|
| 8829 |
var current *StatusItem |
| 8830 |
currentItem := t.currentItem() |
| 8831 |
if currentItem != nil { |
| 8832 |
item := t.dumpItem(currentItem) |
| 8833 |
current = &item |
| 8834 |
} |
| 8835 |
|
| 8836 |
dump := Status{ |
| 8837 |
Reading: t.reading, |
| 8838 |
Progress: t.progress, |
| 8839 |
Query: string(t.input), |
| 8840 |
Position: t.cy, |
| 8841 |
Sort: t.sort, |
| 8842 |
TotalCount: t.count, |
| 8843 |
MatchCount: t.resultMerger.Length(), |
| 8844 |
Current: current, |
| 8845 |
Matches: matches, |
| 8846 |
Selected: selected, |
| 8847 |
} |
| 8848 |
bytes, _ := json.Marshal(&dump) // TODO: Errors? |
| 8849 |
return string(bytes) |
| 8850 |
} |