summaryrefslogtreecommitdiff
path: root/widgets/JttyLiveEntry.hpp
blob: fc4810d840630bc06d27c48ba4c2b62dd4779a9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// -*- Mode: C++ -*-
#ifndef JTTY_LIVE_ENTRY_HPP
#define JTTY_LIVE_ENTRY_HPP

#include <QString>
#include <QStringList>

namespace Jtty
{
  // Widest lookahead try_compact() uses (lib/jtty/jtty_mod.f90, words(3)); holding back this many trailing words guarantees an atom in progress is never split by an early commit.
  inline constexpr int maxCompactAtomWords = 3;

  struct IncrementalCommitPlan
  {
    QString text;        // Text to pack and send now; empty means nothing yet.
    int length {0};       // uncommittedText.left(length) == text, exactly.
  };

  // Number of complete (space-terminated) words in uncommittedText -- a word still being typed (no trailing space yet) doesn't count. Exposed so callers can gate on how much has piled up, not just whether anything has.
  inline int completeWordCount (QString const& uncommittedText)
  {
    if (uncommittedText.isEmpty ()) return 0;
    bool const endsWithCompleteWord = uncommittedText.back () == QLatin1Char {' '};
    QStringList const words = uncommittedText.split (
      QLatin1Char {' '}, Qt::SkipEmptyParts);
    return endsWithCompleteWord ? words.size () : words.size () - 1;
  }

  // Releases uncommittedText up to its trailing holdbackWords complete words (plus any partial word), since a compact atom there could still be extended by what's typed next; forceFlush releases all of it (newline/segment-limit boundary). Assumes single-space-normalized input, matching prepareTransmitText's convention.
  inline IncrementalCommitPlan planIncrementalCommit (
      QString const& uncommittedText, bool forceFlush = false,
      int holdbackWords = maxCompactAtomWords)
  {
    if (uncommittedText.isEmpty ()) return {};
    if (forceFlush) return {uncommittedText, uncommittedText.size ()};

    int const commitWordCount = completeWordCount (uncommittedText) - holdbackWords;
    if (commitWordCount <= 0) return {};

    // Advance to the end of the commitWordCount-th word's trailing space, so the remainder starts cleanly at the next word.
    int length = 0;
    int wordsSeen = 0;
    while (wordsSeen < commitWordCount) {
      int const spaceAt = uncommittedText.indexOf (QLatin1Char {' '}, length);
      Q_ASSERT (spaceAt >= 0);  // completeWordCount already bounds this walk.
      length = spaceAt + 1;
      ++wordsSeen;
    }
    return {uncommittedText.left (length), length};
  }
}

#endif