summaryrefslogtreecommitdiffstats
path: root/infrastructure/ace/www/undomodule.js
blob: b8a56f91096a5f3ffaba657b58af29382bcaa5b2 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/**
 * Copyright 2009 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


undoModule = (function() {
  var stack = (function() {
    var stackElements = [];
    // two types of stackElements:
    // 1) { elementType: UNDOABLE_EVENT, eventType: "anything", [backset: <changeset>,]
    //      [selStart: <char number>, selEnd: <char number>, selFocusAtStart: <boolean>] }
    // 2) { elementType: EXTERNAL_CHANGE, changeset: <changeset> }
    // invariant: no two consecutive EXTERNAL_CHANGEs
    var numUndoableEvents = 0;

    var UNDOABLE_EVENT = "undoableEvent";
    var EXTERNAL_CHANGE = "externalChange";

    function clearStack() {
      stackElements.length = 0;
      stackElements.push({ elementType: UNDOABLE_EVENT, eventType: "bottom" });
      numUndoableEvents = 1;
    }
    clearStack();

    function pushEvent(event) {
      var e = extend({}, event);
      e.elementType = UNDOABLE_EVENT;
      stackElements.push(e);
      numUndoableEvents++;
      //dmesg("pushEvent backset: "+event.backset);
    }

    function pushExternalChange(cs) {
      var idx = stackElements.length-1;
      if (stackElements[idx].elementType == EXTERNAL_CHANGE) {
	stackElements[idx].changeset = Changeset.compose(stackElements[idx].changeset, cs, getAPool());
      }
      else {
	stackElements.push({elementType: EXTERNAL_CHANGE, changeset: cs});
      }
    }

    function _exposeEvent(nthFromTop) {
      // precond: 0 <= nthFromTop < numUndoableEvents
      var targetIndex = stackElements.length - 1 - nthFromTop;
      var idx = stackElements.length - 1;
      while (idx > targetIndex || stackElements[idx].elementType == EXTERNAL_CHANGE) {
	if (stackElements[idx].elementType == EXTERNAL_CHANGE) {
	  var ex = stackElements[idx];
	  var un = stackElements[idx-1];
	  if (un.backset) {
	    var excs = ex.changeset;
	    var unbs = un.backset;
	    un.backset = Changeset.follow(excs, un.backset, false, getAPool());
	    ex.changeset = Changeset.follow(unbs, ex.changeset, true, getAPool());
	    if ((typeof un.selStart) == "number") {
	      var newSel = Changeset.characterRangeFollow(excs, un.selStart, un.selEnd);
	      un.selStart = newSel[0];
	      un.selEnd = newSel[1];
	      if (un.selStart == un.selEnd) {
		un.selFocusAtStart = false;
	      }
	    }
	  }
	  stackElements[idx-1] = ex;
	  stackElements[idx] = un;
	  if (idx >= 2 && stackElements[idx-2].elementType == EXTERNAL_CHANGE) {
	    ex.changeset = Changeset.compose(stackElements[idx-2].changeset,
					     ex.changeset, getAPool());
	    stackElements.splice(idx-2, 1);
	    idx--;
	  }
	}
	else {
	  idx--;
	}
      }
    }

    function getNthFromTop(n) {
      // precond: 0 <= n < numEvents()
      _exposeEvent(n);
      return stackElements[stackElements.length - 1 - n];
    }

    function numEvents() {
      return numUndoableEvents;
    }

    function popEvent() {
      // precond: numEvents() > 0
      _exposeEvent(0);
      numUndoableEvents--;
      return stackElements.pop();
    }

    return {numEvents:numEvents, popEvent:popEvent, pushEvent: pushEvent,
	    pushExternalChange: pushExternalChange, clearStack: clearStack,
	    getNthFromTop:getNthFromTop};
  })();

  // invariant: stack always has at least one undoable event

  var undoPtr = 0; // zero-index from top of stack, 0 == top

  function clearHistory() {
    stack.clearStack();
    undoPtr = 0;
  }

  function _charOccurrences(str, c) {
    var i = 0;
    var count = 0;
    while (i >= 0 && i < str.length) {
      i = str.indexOf(c, i);
      if (i >= 0) {
	count++;
	i++;
      }
    }
    return count;
  }

  function _opcodeOccurrences(cs, opcode) {
    return _charOccurrences(Changeset.unpack(cs).ops, opcode);
  }

  function _mergeChangesets(cs1, cs2) {
    if (! cs1) return cs2;
    if (! cs2) return cs1;

    // Rough heuristic for whether changesets should be considered one action:
    // each does exactly one insertion, no dels, and the composition does also; or
    // each does exactly one deletion, no ins, and the composition does also.
    // A little weird in that it won't merge "make bold" with "insert char"
    // but will merge "make bold and insert char" with "insert char",
    // though that isn't expected to come up.
    var plusCount1 = _opcodeOccurrences(cs1, '+');
    var plusCount2 = _opcodeOccurrences(cs2, '+');
    var minusCount1 = _opcodeOccurrences(cs1, '-');
    var minusCount2 = _opcodeOccurrences(cs2, '-');
    if (plusCount1 == 1 && plusCount2 == 1 && minusCount1 == 0 && minusCount2 == 0) {
      var merge = Changeset.compose(cs1, cs2, getAPool());
      var plusCount3 = _opcodeOccurrences(merge, '+');
      var minusCount3 = _opcodeOccurrences(merge, '-');
      if (plusCount3 == 1 && minusCount3 == 0) {
	return merge;
      }
    }
    else if (plusCount1 == 0 && plusCount2 == 0 && minusCount1 == 1 && minusCount2 == 1) {
      var merge = Changeset.compose(cs1, cs2, getAPool());
      var plusCount3 = _opcodeOccurrences(merge, '+');
      var minusCount3 = _opcodeOccurrences(merge, '-');
      if (plusCount3 == 0 && minusCount3 == 1) {
	return merge;
      }
    }
    return null;
  }

  function reportEvent(event) {
    var topEvent = stack.getNthFromTop(0);

    function applySelectionToTop() {
      if ((typeof event.selStart) == "number") {
	topEvent.selStart = event.selStart;
	topEvent.selEnd = event.selEnd;
	topEvent.selFocusAtStart = event.selFocusAtStart;
      }
    }

    if ((! event.backset) || Changeset.isIdentity(event.backset)) {
      applySelectionToTop();
    }
    else {
      var merged = false;
      if (topEvent.eventType == event.eventType) {
	var merge = _mergeChangesets(event.backset, topEvent.backset);
	if (merge) {
	  topEvent.backset = merge;
	  //dmesg("reportEvent merge: "+merge);
	  applySelectionToTop();
	  merged = true;
	}
      }
      if (! merged) {
	stack.pushEvent(event);
      }
      undoPtr = 0;
    }

  }

  function reportExternalChange(changeset) {
    if (changeset && ! Changeset.isIdentity(changeset)) {
      stack.pushExternalChange(changeset);
    }
  }

  function _getSelectionInfo(event) {
    if ((typeof event.selStart) != "number") {
      return null;
    }
    else {
      return {selStart: event.selStart, selEnd: event.selEnd,
	      selFocusAtStart: event.selFocusAtStart};
    }
  }

  // For "undo" and "redo", the change event must be returned
  // by eventFunc and NOT reported through the normal mechanism.
  // "eventFunc" should take a changeset and an optional selection info object,
  // or can be called with no arguments to mean that no undo is possible.
  // "eventFunc" will be called exactly once.

  function performUndo(eventFunc) {
    if (undoPtr < stack.numEvents()-1) {
      var backsetEvent = stack.getNthFromTop(undoPtr);
      var selectionEvent = stack.getNthFromTop(undoPtr+1);
      var undoEvent = eventFunc(backsetEvent.backset, _getSelectionInfo(selectionEvent));
      stack.pushEvent(undoEvent);
      undoPtr += 2;
    }
    else eventFunc();
  }

  function performRedo(eventFunc) {
    if (undoPtr >= 2) {
      var backsetEvent = stack.getNthFromTop(0);
      var selectionEvent = stack.getNthFromTop(1);
      eventFunc(backsetEvent.backset, _getSelectionInfo(selectionEvent));
      stack.popEvent();
      undoPtr -= 2;
    }
    else eventFunc();
  }

  function getAPool() {
    return undoModule.apool;
  }

  return {clearHistory:clearHistory, reportEvent:reportEvent, reportExternalChange:reportExternalChange,
	  performUndo:performUndo, performRedo:performRedo, enabled: true,
          apool: null}; // apool is filled in by caller
})();