fix for crash with toggle-drag on a popup (when the popup is closed while dragging).
[blender.git] / source / blender / editors / interface / interface_handlers.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_handlers.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <assert.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_sensor_types.h"
42 #include "DNA_controller_types.h"
43 #include "DNA_actuator_types.h"
44
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48
49 #include "BLI_math.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_string_cursor_utf8.h"
53
54 #include "BLF_translation.h"
55
56 #include "PIL_time.h"
57
58 #include "BKE_blender.h"
59 #include "BKE_colortools.h"
60 #include "BKE_context.h"
61 #include "BKE_idprop.h"
62 #include "BKE_report.h"
63 #include "BKE_texture.h"
64 #include "BKE_tracking.h"
65 #include "BKE_unit.h"
66 #include "BKE_paint.h"
67
68 #include "ED_screen.h"
69 #include "ED_util.h"
70 #include "ED_keyframing.h"
71
72 #include "UI_interface.h"
73
74 #include "BLF_api.h"
75
76 #include "interface_intern.h"
77
78 #include "RNA_access.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 /* place the mouse at the scaled down location when un-grabbing */
84 #define USE_CONT_MOUSE_CORRECT
85 /* support dragging toggle buttons */
86 #define USE_DRAG_TOGGLE
87
88 /* so we can avoid very small mouse-moves from jumping away from keyboard navigation [#34936] */
89 #define USE_KEYNAV_LIMIT
90
91 /* proto */
92 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to);
93 static void ui_add_link(bContext *C, uiBut *from, uiBut *to);
94 static int ui_do_but_EXIT(bContext *C, uiBut *but, struct uiHandleButtonData *data, const wmEvent *event);
95
96 #ifdef USE_KEYNAV_LIMIT
97 static void ui_mouse_motion_keynav_init(struct uiKeyNavLock *keynav, const wmEvent *event);
98 static bool ui_mouse_motion_keynav_test(struct uiKeyNavLock *keynav, const wmEvent *event);
99 #endif
100
101 /***************** structs and defines ****************/
102
103 #define BUTTON_TOOLTIP_DELAY        0.500
104 #define BUTTON_FLASH_DELAY          0.020
105 #define MENU_SCROLL_INTERVAL        0.1
106 #define BUTTON_AUTO_OPEN_THRESH     0.3
107 #define BUTTON_MOUSE_TOWARDS_THRESH 1.0
108 /* pixels to move the cursor to get out of keyboard navigation */
109 #define BUTTON_KEYNAV_PX_LIMIT      4
110
111 typedef enum uiButtonActivateType {
112         BUTTON_ACTIVATE_OVER,
113         BUTTON_ACTIVATE,
114         BUTTON_ACTIVATE_APPLY,
115         BUTTON_ACTIVATE_TEXT_EDITING,
116         BUTTON_ACTIVATE_OPEN
117 } uiButtonActivateType;
118
119 typedef enum uiHandleButtonState {
120         BUTTON_STATE_INIT,
121         BUTTON_STATE_HIGHLIGHT,
122         BUTTON_STATE_WAIT_FLASH,
123         BUTTON_STATE_WAIT_RELEASE,
124         BUTTON_STATE_WAIT_KEY_EVENT,
125         BUTTON_STATE_NUM_EDITING,
126         BUTTON_STATE_TEXT_EDITING,
127         BUTTON_STATE_TEXT_SELECTING,
128         BUTTON_STATE_MENU_OPEN,
129         BUTTON_STATE_WAIT_DRAG,
130         BUTTON_STATE_EXIT
131 } uiHandleButtonState;
132
133 typedef struct uiHandleButtonData {
134         wmWindowManager *wm;
135         wmWindow *window;
136         ARegion *region;
137
138         bool interactive;
139
140         /* overall state */
141         uiHandleButtonState state;
142         int retval;
143         /* booleans (could be made into flags) */
144         bool cancel, escapecancel;
145         bool applied, applied_interactive;
146         wmTimer *flashtimer;
147
148         /* edited value */
149         char *str, *origstr;
150         double value, origvalue, startvalue;
151         float vec[3], origvec[3];
152         int togdual, togonly;
153         ColorBand *coba;
154
155         /* tooltip */
156         ARegion *tooltip;
157         wmTimer *tooltiptimer;
158         
159         /* auto open */
160         bool used_mouse;
161         wmTimer *autoopentimer;
162
163         /* text selection/editing */
164         int maxlen, selextend, selstartx;
165
166         /* number editing / dragging */
167         /* coords are Window/uiBlock relative (depends on the button) */
168         int draglastx, draglasty;
169         int dragstartx, dragstarty;
170         bool dragchange, draglock;
171         int dragsel;
172         float dragf, dragfstart;
173         CBData *dragcbd;
174
175 #ifdef USE_CONT_MOUSE_CORRECT
176         /* when ungrabbing buttons which are #ui_is_a_warp_but(), we may want to position them
177          * FLT_MAX signifies do-nothing, use #ui_block_to_window_fl() to get this into a usable space  */
178         float ungrab_mval[2];
179 #endif
180
181         /* menu open (watch uiFreeActiveButtons) */
182         uiPopupBlockHandle *menu;
183         int menuretval;
184         
185         /* search box (watch uiFreeActiveButtons) */
186         ARegion *searchbox;
187 #ifdef USE_KEYNAV_LIMIT
188         struct uiKeyNavLock searchbox_keynav_state;
189 #endif
190
191         /* post activate */
192         uiButtonActivateType posttype;
193         uiBut *postbut;
194 } uiHandleButtonData;
195
196 typedef struct uiAfterFunc {
197         struct uiAfterFunc *next, *prev;
198
199         uiButHandleFunc func;
200         void *func_arg1;
201         void *func_arg2;
202         
203         uiButHandleNFunc funcN;
204         void *func_argN;
205
206         uiButHandleRenameFunc rename_func;
207         void *rename_arg1;
208         void *rename_orig;
209         
210         uiBlockHandleFunc handle_func;
211         void *handle_func_arg;
212         int retval;
213
214         uiMenuHandleFunc butm_func;
215         void *butm_func_arg;
216         int a2;
217
218         wmOperatorType *optype;
219         int opcontext;
220         PointerRNA *opptr;
221
222         PointerRNA rnapoin;
223         PropertyRNA *rnaprop;
224
225         bContextStore *context;
226
227         char undostr[BKE_UNDO_STR_MAX];
228
229         int autokey;
230 } uiAfterFunc;
231
232 static bool ui_but_contains_pt(uiBut *but, int mx, int my);
233 static bool ui_mouse_inside_button(ARegion *ar, uiBut *but, int x, int y);
234 static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState state);
235 static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *userdata);
236 static void ui_handle_button_activate(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
237 static void button_timers_tooltip_remove(bContext *C, uiBut *but);
238
239 /* ******************** menu navigation helpers ************** */
240
241 /* assumes event type is MOUSEPAN */
242 void ui_pan_to_scroll(const wmEvent *event, int *type, int *val)
243 {
244         static int lastdy = 0;
245         int dy = event->prevy - event->y;
246
247         /* This event should be originally from event->type,
248          * converting wrong event into wheel is bad, see [#33803] */
249         BLI_assert(*type == MOUSEPAN);
250
251         /* sign differs, reset */
252         if ((dy > 0 && lastdy < 0) || (dy < 0 && lastdy > 0)) {
253                 lastdy = dy;
254         }
255         else {
256                 lastdy += dy;
257                 
258                 if (ABS(lastdy) > (int)UI_UNIT_Y) {
259                         if (U.uiflag2 & USER_TRACKPAD_NATURAL)
260                                 dy = -dy;
261                         
262                         *val = KM_PRESS;
263                         
264                         if (dy > 0)
265                                 *type = WHEELUPMOUSE;
266                         else
267                                 *type = WHEELDOWNMOUSE;
268                         
269                         lastdy = 0;
270                 }
271         }
272 }
273
274 static bool ui_but_editable(uiBut *but)
275 {
276         return ELEM5(but->type, LABEL, SEPR, ROUNDBOX, LISTBOX, PROGRESSBAR);
277 }
278
279 static uiBut *ui_but_prev(uiBut *but)
280 {
281         while (but->prev) {
282                 but = but->prev;
283                 if (!ui_but_editable(but)) return but;
284         }
285         return NULL;
286 }
287
288 static uiBut *ui_but_next(uiBut *but)
289 {
290         while (but->next) {
291                 but = but->next;
292                 if (!ui_but_editable(but)) return but;
293         }
294         return NULL;
295 }
296
297 static uiBut *ui_but_first(uiBlock *block)
298 {
299         uiBut *but;
300         
301         but = block->buttons.first;
302         while (but) {
303                 if (!ui_but_editable(but)) return but;
304                 but = but->next;
305         }
306         return NULL;
307 }
308
309 static uiBut *ui_but_last(uiBlock *block)
310 {
311         uiBut *but;
312         
313         but = block->buttons.last;
314         while (but) {
315                 if (!ui_but_editable(but)) return but;
316                 but = but->prev;
317         }
318         return NULL;
319 }
320
321 static bool ui_is_a_warp_but(uiBut *but)
322 {
323         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
324                 if (ELEM7(but->type, NUM, NUMSLI, NUMABS, HSVCIRCLE, TRACKPREVIEW, HSVCUBE, BUT_CURVE)) {
325                         return true;
326                 }
327         }
328
329         return false;
330 }
331
332 static float ui_mouse_scale_warp_factor(const short shift)
333 {
334         return shift ? 0.05f : 1.0f;
335 }
336
337 static void ui_mouse_scale_warp(uiHandleButtonData *data,
338                                 const float mx, const float my,
339                                 float *r_mx, float *r_my,
340                                 const short shift)
341 {
342         const float fac = ui_mouse_scale_warp_factor(shift);
343         
344         /* slow down the mouse, this is fairly picky */
345         *r_mx = (data->dragstartx * (1.0f - fac) + mx * fac);
346         *r_my = (data->dragstarty * (1.0f - fac) + my * fac);
347 }
348
349 /* file selectors are exempt from utf-8 checks */
350 bool ui_is_but_utf8(uiBut *but)
351 {
352         if (but->rnaprop) {
353                 const int subtype = RNA_property_subtype(but->rnaprop);
354                 return !(ELEM4(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME, PROP_BYTESTRING));
355         }
356         else {
357                 return !(but->flag & UI_BUT_NO_UTF8);
358         }
359 }
360
361 /* ********************** button apply/revert ************************/
362
363 static ListBase UIAfterFuncs = {NULL, NULL};
364
365 static void ui_apply_but_func(bContext *C, uiBut *but)
366 {
367         uiAfterFunc *after;
368         uiBlock *block = but->block;
369
370         /* these functions are postponed and only executed after all other
371          * handling is done, i.e. menus are closed, in order to avoid conflicts
372          * with these functions removing the buttons we are working with */
373
374         if (but->func || but->funcN || block->handle_func || but->rename_func ||
375             (but->type == BUTM && block->butm_func) || but->optype || but->rnaprop)
376         {
377                 after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
378
379                 if (but->func && ELEM(but, but->func_arg1, but->func_arg2)) {
380                         /* exception, this will crash due to removed button otherwise */
381                         but->func(C, but->func_arg1, but->func_arg2);
382                 }
383                 else
384                         after->func = but->func;
385
386                 after->func_arg1 = but->func_arg1;
387                 after->func_arg2 = but->func_arg2;
388
389                 after->funcN = but->funcN;
390                 after->func_argN = MEM_dupallocN(but->func_argN);
391
392                 after->rename_func = but->rename_func;
393                 after->rename_arg1 = but->rename_arg1;
394                 after->rename_orig = but->rename_orig; /* needs free! */
395
396                 after->handle_func = block->handle_func;
397                 after->handle_func_arg = block->handle_func_arg;
398                 after->retval = but->retval;
399
400                 if (but->type == BUTM) {
401                         after->butm_func = block->butm_func;
402                         after->butm_func_arg = block->butm_func_arg;
403                         after->a2 = but->a2;
404                 }
405
406                 after->optype = but->optype;
407                 after->opcontext = but->opcontext;
408                 after->opptr = but->opptr;
409
410                 after->rnapoin = but->rnapoin;
411                 after->rnaprop = but->rnaprop;
412
413                 if (but->context)
414                         after->context = CTX_store_copy(but->context);
415
416                 but->optype = NULL;
417                 but->opcontext = 0;
418                 but->opptr = NULL;
419
420                 BLI_addtail(&UIAfterFuncs, after);
421         }
422 }
423
424 /* typically call ui_apply_undo(), ui_apply_autokey() */
425 static void ui_apply_undo(uiBut *but)
426 {
427         uiAfterFunc *after;
428
429         if (but->flag & UI_BUT_UNDO) {
430                 const char *str = NULL;
431
432                 /* define which string to use for undo */
433                 if (ELEM(but->type, LINK, INLINK)) str = "Add button link";
434                 else if (ELEM(but->type, MENU, ICONTEXTROW)) str = but->drawstr;
435                 else if (but->drawstr[0]) str = but->drawstr;
436                 else str = but->tip;
437
438                 /* fallback, else we don't get an undo! */
439                 if (str == NULL || str[0] == '\0') {
440                         str = "Unknown Action";
441                 }
442
443                 /* delayed, after all other funcs run, popups are closed, etc */
444                 after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
445                 BLI_strncpy(after->undostr, str, sizeof(after->undostr));
446                 BLI_addtail(&UIAfterFuncs, after);
447         }
448 }
449
450 static void ui_apply_autokey(bContext *C, uiBut *but)
451 {
452         Scene *scene = CTX_data_scene(C);
453
454         /* try autokey */
455         ui_but_anim_autokey(C, but, scene, scene->r.cfra);
456
457         /* make a little report about what we've done! */
458         if (but->rnaprop) {
459                 char *buf = WM_prop_pystring_assign(C, &but->rnapoin, but->rnaprop, but->rnaindex);
460                 if (buf) {
461                         BKE_report(CTX_wm_reports(C), RPT_PROPERTY, buf);
462                         MEM_freeN(buf);
463
464                         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
465                 }
466         }
467 }
468
469 static void ui_apply_but_funcs_after(bContext *C)
470 {
471         uiAfterFunc *afterf, after;
472         PointerRNA opptr;
473         ListBase funcs;
474
475         /* copy to avoid recursive calls */
476         funcs = UIAfterFuncs;
477         UIAfterFuncs.first = UIAfterFuncs.last = NULL;
478
479         for (afterf = funcs.first; afterf; afterf = after.next) {
480                 after = *afterf; /* copy to avoid memleak on exit() */
481                 BLI_freelinkN(&funcs, afterf);
482
483                 if (after.context)
484                         CTX_store_set(C, after.context);
485
486                 if (after.opptr) {
487                         /* free in advance to avoid leak on exit */
488                         opptr = *after.opptr,
489                         MEM_freeN(after.opptr);
490                 }
491
492                 if (after.optype)
493                         WM_operator_name_call(C, after.optype->idname, after.opcontext, (after.opptr) ? &opptr : NULL);
494
495                 if (after.opptr)
496                         WM_operator_properties_free(&opptr);
497
498                 if (after.rnapoin.data)
499                         RNA_property_update(C, &after.rnapoin, after.rnaprop);
500
501                 if (after.context) {
502                         CTX_store_set(C, NULL);
503                         CTX_store_free(after.context);
504                 }
505
506                 if (after.func)
507                         after.func(C, after.func_arg1, after.func_arg2);
508                 if (after.funcN)
509                         after.funcN(C, after.func_argN, after.func_arg2);
510                 if (after.func_argN)
511                         MEM_freeN(after.func_argN);
512                 
513                 if (after.handle_func)
514                         after.handle_func(C, after.handle_func_arg, after.retval);
515                 if (after.butm_func)
516                         after.butm_func(C, after.butm_func_arg, after.a2);
517                 
518                 if (after.rename_func)
519                         after.rename_func(C, after.rename_arg1, after.rename_orig);
520                 if (after.rename_orig)
521                         MEM_freeN(after.rename_orig);
522                 
523                 if (after.undostr[0])
524                         ED_undo_push(C, after.undostr);
525         }
526 }
527
528 static void ui_apply_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data)
529 {
530         ui_apply_but_func(C, but);
531
532         data->retval = but->retval;
533         data->applied = true;
534 }
535
536 static void ui_apply_but_BUTM(bContext *C, uiBut *but, uiHandleButtonData *data)
537 {
538         ui_set_but_val(but, but->hardmin);
539         ui_apply_but_func(C, but);
540
541         data->retval = but->retval;
542         data->applied = true;
543 }
544
545 static void ui_apply_but_BLOCK(bContext *C, uiBut *but, uiHandleButtonData *data)
546 {
547         if (ELEM3(but->type, MENU, ICONROW, ICONTEXTROW))
548                 ui_set_but_val(but, data->value);
549
550         ui_check_but(but);
551         ui_apply_but_func(C, but);
552         data->retval = but->retval;
553         data->applied = true;
554 }
555
556 static void ui_apply_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data)
557 {
558         double value;
559         int w, lvalue, push;
560         
561         /* local hack... */
562         if (but->type == BUT_TOGDUAL && data->togdual) {
563                 if (but->pointype == UI_BUT_POIN_SHORT) {
564                         but->poin += 2;
565                 }
566                 else if (but->pointype == UI_BUT_POIN_INT) {
567                         but->poin += 4;
568                 }
569         }
570         
571         value = ui_get_but_val(but);
572         lvalue = (int)value;
573         
574         if (but->bit) {
575                 w = UI_BITBUT_TEST(lvalue, but->bitnr);
576                 if (w) lvalue = UI_BITBUT_CLR(lvalue, but->bitnr);
577                 else   lvalue = UI_BITBUT_SET(lvalue, but->bitnr);
578                 
579                 if (but->type == TOGR) {
580                         if (!data->togonly) {
581                                 lvalue = 1 << (but->bitnr);
582         
583                                 ui_set_but_val(but, (double)lvalue);
584                         }
585                         else {
586                                 if (lvalue == 0) lvalue = 1 << (but->bitnr);
587                         }
588                 }
589                 
590                 ui_set_but_val(but, (double)lvalue);
591                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
592         }
593         else {
594                 
595                 if (value == 0.0) push = 1;
596                 else push = 0;
597                 
598                 if (ELEM3(but->type, TOGN, ICONTOGN, OPTIONN)) push = !push;
599                 ui_set_but_val(but, (double)push);
600                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
601         }
602         
603         /* end local hack... */
604         if (but->type == BUT_TOGDUAL && data->togdual) {
605                 if (but->pointype == UI_BUT_POIN_SHORT) {
606                         but->poin -= 2;
607                 }
608                 else if (but->pointype == UI_BUT_POIN_INT) {
609                         but->poin -= 4;
610                 }
611         }
612         
613         ui_apply_but_func(C, but);
614
615         data->retval = but->retval;
616         data->applied = true;
617 }
618
619 static void ui_apply_but_ROW(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
620 {
621         uiBut *bt;
622         
623         ui_set_but_val(but, but->hardmax);
624         
625         /* states of other row buttons */
626         for (bt = block->buttons.first; bt; bt = bt->next)
627                 if (bt != but && bt->poin == but->poin && ELEM(bt->type, ROW, LISTROW))
628                         ui_check_but(bt);
629         
630         ui_apply_but_func(C, but);
631
632         data->retval = but->retval;
633         data->applied = true;
634 }
635
636 static void ui_apply_but_TEX(bContext *C, uiBut *but, uiHandleButtonData *data)
637 {
638         if (!data->str)
639                 return;
640
641         ui_set_but_string(C, but, data->str);
642         ui_check_but(but);
643
644         /* give butfunc the original text too */
645         /* feature used for bone renaming, channels, etc */
646         /* afterfunc frees origstr */
647         but->rename_orig = data->origstr;
648         data->origstr = NULL;
649         ui_apply_but_func(C, but);
650
651         data->retval = but->retval;
652         data->applied = true;
653 }
654
655 static void ui_apply_but_NUM(bContext *C, uiBut *but, uiHandleButtonData *data)
656 {
657         if (data->str) {
658                 if (ui_set_but_string(C, but, data->str)) {
659                         data->value = ui_get_but_val(but);
660                 }
661                 else {
662                         data->cancel = true;
663                         return;
664                 }
665         }
666         else
667                 ui_set_but_val(but, data->value);
668
669         ui_check_but(but);
670         ui_apply_but_func(C, but);
671
672         data->retval = but->retval;
673         data->applied = true;
674 }
675
676 static void ui_apply_but_TOG3(bContext *C, uiBut *but, uiHandleButtonData *data)
677
678         if (but->pointype == UI_BUT_POIN_SHORT) {
679                 short *sp = (short *)but->poin;
680                 
681                 if (UI_BITBUT_TEST(sp[1], but->bitnr)) {
682                         sp[1] = UI_BITBUT_CLR(sp[1], but->bitnr);
683                         sp[0] = UI_BITBUT_CLR(sp[0], but->bitnr);
684                 }
685                 else if (UI_BITBUT_TEST(sp[0], but->bitnr)) {
686                         sp[1] = UI_BITBUT_SET(sp[1], but->bitnr);
687                 }
688                 else {
689                         sp[0] = UI_BITBUT_SET(sp[0], but->bitnr);
690                 }
691         }
692         else {
693                 if (UI_BITBUT_TEST(*(but->poin + 2), but->bitnr)) {
694                         *(but->poin + 2) = UI_BITBUT_CLR(*(but->poin + 2), but->bitnr);
695                         *(but->poin)     = UI_BITBUT_CLR(*(but->poin),     but->bitnr);
696                 }
697                 else if (UI_BITBUT_TEST(*(but->poin), but->bitnr)) {
698                         *(but->poin + 2) = UI_BITBUT_SET(*(but->poin + 2), but->bitnr);
699                 }
700                 else {
701                         *(but->poin) = UI_BITBUT_SET(*(but->poin), but->bitnr);
702                 }
703         }
704         
705         ui_check_but(but);
706         ui_apply_but_func(C, but);
707         data->retval = but->retval;
708         data->applied = true;
709 }
710
711 static void ui_apply_but_VEC(bContext *C, uiBut *but, uiHandleButtonData *data)
712 {
713         ui_set_but_vectorf(but, data->vec);
714         ui_check_but(but);
715         ui_apply_but_func(C, but);
716
717         data->retval = but->retval;
718         data->applied = true;
719 }
720
721 static void ui_apply_but_COLORBAND(bContext *C, uiBut *but, uiHandleButtonData *data)
722 {
723         ui_apply_but_func(C, but);
724         data->retval = but->retval;
725         data->applied = true;
726 }
727
728 static void ui_apply_but_CURVE(bContext *C, uiBut *but, uiHandleButtonData *data)
729 {
730         ui_apply_but_func(C, but);
731         data->retval = but->retval;
732         data->applied = true;
733 }
734
735 static void ui_apply_but_IDPOIN(bContext *C, uiBut *but, uiHandleButtonData *data)
736 {
737         ui_set_but_string(C, but, data->str);
738         ui_check_but(but);
739         ui_apply_but_func(C, but);
740         data->retval = but->retval;
741         data->applied = true;
742 }
743
744 #ifdef WITH_INTERNATIONAL
745 static void ui_apply_but_CHARTAB(bContext *C, uiBut *but, uiHandleButtonData *data)
746 {
747         ui_apply_but_func(C, but);
748         data->retval = but->retval;
749         data->applied = true;
750 }
751 #endif
752
753 /* ****************** drag drop code *********************** */
754
755 #ifdef USE_DRAG_TOGGLE
756
757 typedef struct uiDragToggleHandle {
758         /* init */
759         bool is_init;
760         bool is_set;
761         float but_cent_start[2];
762         eButType but_type_start;
763
764         bool xy_lock[2];
765         int  xy_last[2];
766 } uiDragToggleHandle;
767
768 static bool ui_drag_toggle_set_xy_xy(bContext *C, ARegion *ar, const bool is_set, const eButType but_type_start,
769                                      const int xy_src[2], const int xy_dst[2])
770 {
771         /* popups such as layers won't re-evaluate on redraw */
772         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
773         bool change = false;
774         uiBlock *block;
775
776         for (block = ar->uiblocks.first; block; block = block->next) {
777                 uiBut *but;
778
779                 float xy_a_block[2] = {UNPACK2(xy_src)};
780                 float xy_b_block[2] = {UNPACK2(xy_dst)};
781
782                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
783                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
784
785                 for (but = block->buttons.first; but; but = but->next) {
786                         if (ui_is_but_interactive(but)) {
787                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
788
789                                         /* execute the button */
790                                         if (ui_is_but_bool(but) && but->type == but_type_start) {
791                                                 /* is it pressed? */
792                                                 bool is_set_but = ui_is_but_push(but);
793                                                 BLI_assert(ui_is_but_bool(but) == true);
794                                                 if (is_set_but != is_set) {
795                                                         uiButExecute(C, but);
796                                                         if (do_check) {
797                                                                 ui_check_but(but);
798                                                         }
799                                                         change = true;
800                                                 }
801                                         }
802                                         /* done */
803
804                                 }
805                         }
806                 }
807         }
808
809         return change;
810 }
811
812 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
813 {
814         ARegion *ar = CTX_wm_region(C);
815         bool do_draw = false;
816         int xy[2];
817
818         /**
819          * Initialize Locking:
820          *
821          * Check if we need to initialize the lock axis by finding if the first
822          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
823          */
824         if (drag_info->is_init == false) {
825                 /* first store the buttons original coords */
826                 uiBut *but = ui_but_find_mouse_over(ar, xy_input[0], xy_input[1]);
827
828                 if (but) {
829                         if (but->flag & UI_BUT_DRAG_LOCK) {
830                                 const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect),
831                                                                BLI_rctf_cent_y(&but->rect)};
832
833                                 /* check if this is a different button, chances are high the button wont move about :) */
834                                 if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
835                                         if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
836                                             fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
837                                         {
838                                                 drag_info->xy_lock[0] = true;
839                                         }
840                                         else {
841                                                 drag_info->xy_lock[1] = true;
842                                         }
843                                         drag_info->is_init = true;
844                                 }
845                         }
846                         else {
847                                 drag_info->is_init = true;
848                         }
849                 }
850         }
851         /* done with axis locking */
852
853
854         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
855         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
856
857
858         /* touch all buttons between last mouse coord and this one */
859         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->but_type_start, drag_info->xy_last, xy);
860
861         if (do_draw) {
862                 ED_region_tag_redraw(ar);
863         }
864
865         copy_v2_v2_int(drag_info->xy_last, xy);
866 }
867
868 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
869 {
870         uiDragToggleHandle *drag_info = userdata;
871         MEM_freeN(drag_info);
872 }
873
874 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
875 {
876         uiDragToggleHandle *drag_info = userdata;
877         bool done = false;
878
879         switch (event->type) {
880                 case LEFTMOUSE:
881                 {
882                         if (event->val != KM_PRESS) {
883                                 done = true;
884                         }
885                         break;
886                 }
887                 case MOUSEMOVE:
888                 {
889                         ui_drag_toggle_set(C, drag_info, &event->x);
890                         break;
891                 }
892         }
893
894         if (done) {
895                 wmWindow *win = CTX_wm_window(C);
896                 WM_event_remove_ui_handler(&win->modalhandlers,
897                                            ui_handler_region_drag_toggle,
898                                            ui_handler_region_drag_toggle_remove,
899                                            drag_info, false);
900                 ui_handler_region_drag_toggle_remove(C, drag_info);
901
902                 WM_event_add_mousemove(C);
903                 return WM_UI_HANDLER_BREAK;
904         }
905         else {
906                 return WM_UI_HANDLER_CONTINUE;
907         }
908 }
909
910 #endif  /* USE_DRAG_TOGGLE */
911
912
913 static bool ui_but_mouse_inside_icon(uiBut *but, ARegion *ar, const wmEvent *event)
914 {
915         rcti rect;
916         int x = event->x, y = event->y;
917         
918         ui_window_to_block(ar, but->block, &x, &y);
919         
920         BLI_rcti_rctf_copy(&rect, &but->rect);
921         
922         if (but->imb) {
923                 /* use button size itself */
924         }
925         else if (but->flag & UI_ICON_LEFT) {
926                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
927         }
928         else {
929                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
930                 rect.xmin += delta / 2;
931                 rect.xmax -= delta / 2;
932         }
933         
934         return BLI_rcti_isect_pt(&rect, x, y);
935 }
936
937 static bool ui_but_start_drag(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
938 {
939         /* prevent other WM gestures to start while we try to drag */
940         WM_gestures_remove(C);
941
942         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
943
944                 button_activate_state(C, but, BUTTON_STATE_EXIT);
945                 data->cancel = true;
946 #ifdef USE_DRAG_TOGGLE
947                 if (ui_is_but_bool(but)) {
948                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
949                         ARegion *ar_prev;
950
951                         drag_info->is_set = ui_is_but_push(but);
952                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
953                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
954                         drag_info->but_type_start = but->type;
955                         copy_v2_v2_int(drag_info->xy_last, &event->x);
956
957                         /* needed for toggle drag on popups */
958                         ar_prev = CTX_wm_region(C);
959                         CTX_wm_region_set(C, data->region);
960
961                         WM_event_add_ui_handler(C, &data->window->modalhandlers,
962                                                 ui_handler_region_drag_toggle,
963                                                 ui_handler_region_drag_toggle_remove,
964                                                 drag_info);
965
966                         CTX_wm_region_set(C, ar_prev);
967                 }
968                 else
969 #endif
970                 {
971                         wmDrag *drag;
972
973                         drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_get_but_val(but));
974                         if (but->imb)
975                                 WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
976                 }
977                 return true;
978         }
979         
980         return false;
981 }
982
983 /* ********************** linklines *********************** */
984
985 static void ui_delete_active_linkline(uiBlock *block)
986 {
987         uiBut *but;
988         uiLink *link;
989         uiLinkLine *line, *nline;
990         int a, b;
991
992         for (but = block->buttons.first; but; but = but->next) {
993                 if (but->type == LINK && but->link) {
994                         for (line = but->link->lines.first; line; line = nline) {
995                                 nline = line->next;
996                                 
997                                 if (line->flag & UI_SELECT) {
998                                         BLI_remlink(&but->link->lines, line);
999                                         
1000                                         link = line->from->link;
1001                                         
1002                                         /* are there more pointers allowed? */
1003                                         if (link->ppoin) {
1004                                                 
1005                                                 if (*(link->totlink) == 1) {
1006                                                         *(link->totlink) = 0;
1007                                                         MEM_freeN(*(link->ppoin));
1008                                                         *(link->ppoin) = NULL;
1009                                                 }
1010                                                 else {
1011                                                         b = 0;
1012                                                         for (a = 0; a < (*(link->totlink)); a++) {
1013                                                                 
1014                                                                 if ((*(link->ppoin))[a] != line->to->poin) {
1015                                                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1016                                                                         b++;
1017                                                                 }
1018                                                         }
1019                                                         (*(link->totlink))--;
1020                                                 }
1021                                         }
1022                                         else {
1023                                                 *(link->poin) = NULL;
1024                                         }
1025                                         
1026                                         MEM_freeN(line);
1027                                 }
1028                         }
1029                 }
1030         }
1031 }
1032
1033
1034 static uiLinkLine *ui_is_a_link(uiBut *from, uiBut *to)
1035 {
1036         uiLinkLine *line;
1037         uiLink *link;
1038         
1039         link = from->link;
1040         if (link) {
1041                 for (line = link->lines.first; line; line = line->next) {
1042                         if (line->from == from && line->to == to) {
1043                                 return line;
1044                         }
1045                 }
1046         }
1047         return NULL;
1048 }
1049
1050 /* XXX BAD BAD HACK, fixme later **************** */
1051 /* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */
1052 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
1053 {
1054         Object *ob = NULL;
1055         bSensor *sens_iter;
1056         bActuator *act_to, *act_iter;
1057         bController *cont;
1058         bController ***sens_from_links;
1059         uiBut *tmp_but;
1060
1061         uiLink *link = from->link;
1062
1063         PointerRNA props_ptr, object_ptr;
1064         
1065         if (link->ppoin)
1066                 sens_from_links = (bController ***)(link->ppoin);
1067         else return;
1068
1069         act_to = (bActuator *)(to->poin);
1070
1071         /* (1) get the object */
1072         CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects)
1073         {
1074                 for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) {
1075                         if (&(sens_iter->links) == sens_from_links) {
1076                                 ob = ob_iter;
1077                                 break;
1078                         }
1079                 }
1080                 if (ob) break;
1081         } CTX_DATA_END;
1082
1083         if (!ob) return;
1084
1085         /* (2) check if the sensor and the actuator are from the same object */
1086         for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) {
1087                 if (act_iter == act_to)
1088                         break;
1089         }
1090
1091         /* only works if the sensor and the actuator are from the same object */
1092         if (!act_iter) return;
1093         
1094         /* in case the linked controller is not the active one */
1095         RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
1096         
1097         WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
1098         RNA_string_set(&props_ptr, "object", ob->id.name + 2);
1099
1100         /* (3) add a new controller */
1101         if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
1102                 cont = (bController *)ob->controllers.last;
1103                 cont->type = CONT_LOGIC_AND; /* Quick fix to make sure we always have an AND controller. It might be nicer to make sure the operator gives us the right one though... */
1104
1105                 /* (4) link the sensor->controller->actuator */
1106                 tmp_but = MEM_callocN(sizeof(uiBut), "uiBut");
1107                 uiSetButLink(tmp_but, (void **)&cont, (void ***)&(cont->links), &(cont->totlinks), from->link->tocode, (int)to->hardmin);
1108                 tmp_but->hardmin = from->link->tocode;
1109                 tmp_but->poin = (char *)cont;
1110
1111                 tmp_but->type = INLINK;
1112                 ui_add_link(C, from, tmp_but);
1113
1114                 tmp_but->type = LINK;
1115                 ui_add_link(C, tmp_but, to);
1116
1117                 /* (5) garbage collection */
1118                 MEM_freeN(tmp_but->link);
1119                 MEM_freeN(tmp_but);
1120         }
1121         WM_operator_properties_free(&props_ptr);
1122 }
1123
1124 static void ui_add_link(bContext *C, uiBut *from, uiBut *to)
1125 {
1126         /* in 'from' we have to add a link to 'to' */
1127         uiLink *link;
1128         uiLinkLine *line;
1129         void **oldppoin;
1130         int a;
1131         
1132         if ((line = ui_is_a_link(from, to))) {
1133                 line->flag |= UI_SELECT;
1134                 ui_delete_active_linkline(from->block);
1135                 return;
1136         }
1137
1138         if (from->type == INLINK && to->type == INLINK) {
1139                 return;
1140         }
1141         else if (from->type == LINK && to->type == INLINK) {
1142                 if (from->link->tocode != (int)to->hardmin) {
1143                         ui_add_smart_controller(C, from, to);
1144                         return;
1145                 }
1146         }
1147         else if (from->type == INLINK && to->type == LINK) {
1148                 if (to->link->tocode == (int)from->hardmin) {
1149                         return;
1150                 }
1151         }
1152         
1153         link = from->link;
1154         
1155         /* are there more pointers allowed? */
1156         if (link->ppoin) {
1157                 oldppoin = *(link->ppoin);
1158                 
1159                 (*(link->totlink))++;
1160                 *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link");
1161                 
1162                 for (a = 0; a < (*(link->totlink)) - 1; a++) {
1163                         (*(link->ppoin))[a] = oldppoin[a];
1164                 }
1165                 (*(link->ppoin))[a] = to->poin;
1166                 
1167                 if (oldppoin) MEM_freeN(oldppoin);
1168         }
1169         else {
1170                 *(link->poin) = to->poin;
1171         }
1172         
1173 }
1174
1175
1176 static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data)
1177 {
1178         ARegion *ar = CTX_wm_region(C);
1179         uiBut *bt;
1180         
1181         for (bt = but->block->buttons.first; bt; bt = bt->next) {
1182                 if (ui_mouse_inside_button(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) )
1183                         break;
1184         }
1185         if (bt && bt != but) {
1186                 if (!ELEM(bt->type, LINK, INLINK) || !ELEM(but->type, LINK, INLINK))
1187                         return;
1188                 
1189                 if (but->type == LINK) ui_add_link(C, but, bt);
1190                 else ui_add_link(C, bt, but);
1191
1192                 ui_apply_but_func(C, but);
1193                 data->retval = but->retval;
1194         }
1195         data->applied = true;
1196 }
1197
1198 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1199 {
1200         ui_apply_but_func(C, but);
1201         data->retval = but->retval;
1202         data->applied = true;
1203 }
1204
1205 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1206 {
1207         ui_apply_but_func(C, but);
1208         data->retval = but->retval;
1209         data->applied = true;
1210 }
1211
1212 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1213 {
1214         ui_apply_but_func(C, but);
1215         data->retval = but->retval;
1216         data->applied = true;
1217 }
1218
1219 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1220 {
1221         ui_apply_but_func(C, but);
1222         data->retval = but->retval;
1223         data->applied = true;
1224 }
1225
1226
1227 static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1228 {
1229         char *editstr;
1230         double *editval;
1231         float *editvec;
1232         ColorBand *editcoba;
1233         CurveMapping *editcumap;
1234
1235         data->retval = 0;
1236
1237         /* if we cancel and have not applied yet, there is nothing to do,
1238          * otherwise we have to restore the original value again */
1239         if (data->cancel) {
1240                 if (!data->applied)
1241                         return;
1242
1243                 if (data->str) MEM_freeN(data->str);
1244                 data->str = data->origstr;
1245                 data->origstr = NULL;
1246                 data->value = data->origvalue;
1247                 data->origvalue = 0.0;
1248                 copy_v3_v3(data->vec, data->origvec);
1249                 data->origvec[0] = data->origvec[1] = data->origvec[2] = 0.0f;
1250         }
1251         else {
1252                 /* we avoid applying interactive edits a second time
1253                  * at the end with the appliedinteractive flag */
1254                 if (interactive) {
1255                         data->applied_interactive = true;
1256                 }
1257                 else if (data->applied_interactive) {
1258                         return;
1259                 }
1260         }
1261
1262         /* ensures we are writing actual values */
1263         editstr = but->editstr;
1264         editval = but->editval;
1265         editvec = but->editvec;
1266         editcoba = but->editcoba;
1267         editcumap = but->editcumap;
1268         but->editstr = NULL;
1269         but->editval = NULL;
1270         but->editvec = NULL;
1271         but->editcoba = NULL;
1272         but->editcumap = NULL;
1273
1274         /* handle different types */
1275         switch (but->type) {
1276                 case BUT:
1277                         ui_apply_but_BUT(C, but, data);
1278                         break;
1279                 case TEX:
1280                 case SEARCH_MENU_UNLINK:
1281                 case SEARCH_MENU:
1282                         ui_apply_but_TEX(C, but, data);
1283                         break;
1284                 case TOGBUT: 
1285                 case TOG: 
1286                 case TOGR: 
1287                 case ICONTOG:
1288                 case ICONTOGN:
1289                 case TOGN:
1290                 case BUT_TOGDUAL:
1291                 case OPTION:
1292                 case OPTIONN:
1293                         ui_apply_but_TOG(C, but, data);
1294                         break;
1295                 case ROW:
1296                 case LISTROW:
1297                         ui_apply_but_ROW(C, block, but, data);
1298                         break;
1299                 case SCROLL:
1300                 case NUM:
1301                 case NUMABS:
1302                 case SLI:
1303                 case NUMSLI:
1304                         ui_apply_but_NUM(C, but, data);
1305                         break;
1306                 case TOG3:
1307                         ui_apply_but_TOG3(C, but, data);
1308                         break;
1309                 case MENU:
1310                 case ICONROW:
1311                 case ICONTEXTROW:
1312                 case BLOCK:
1313                 case PULLDOWN:
1314                         ui_apply_but_BLOCK(C, but, data);
1315                         break;
1316                 case COLOR:
1317                         if (data->cancel)
1318                                 ui_apply_but_VEC(C, but, data);
1319                         else
1320                                 ui_apply_but_BLOCK(C, but, data);
1321                         break;
1322                 case BUTM:
1323                         ui_apply_but_BUTM(C, but, data);
1324                         break;
1325                 case BUT_NORMAL:
1326                 case HSVCUBE:
1327                 case HSVCIRCLE:
1328                         ui_apply_but_VEC(C, but, data);
1329                         break;
1330                 case BUT_COLORBAND:
1331                         ui_apply_but_COLORBAND(C, but, data);
1332                         break;
1333                 case BUT_CURVE:
1334                         ui_apply_but_CURVE(C, but, data);
1335                         break;
1336                 case IDPOIN:
1337                         ui_apply_but_IDPOIN(C, but, data);
1338                         break;
1339 #ifdef WITH_INTERNATIONAL
1340                 case CHARTAB:
1341                         ui_apply_but_CHARTAB(C, but, data);
1342                         break;
1343 #endif
1344                 case KEYEVT:
1345                 case HOTKEYEVT:
1346                         ui_apply_but_BUT(C, but, data);
1347                         break;
1348                 case LINK:
1349                 case INLINK:
1350                         ui_apply_but_LINK(C, but, data);
1351                         break;
1352                 case BUT_IMAGE:
1353                         ui_apply_but_IMAGE(C, but, data);
1354                         break;
1355                 case HISTOGRAM:
1356                         ui_apply_but_HISTOGRAM(C, but, data);
1357                         break;
1358                 case WAVEFORM:
1359                         ui_apply_but_WAVEFORM(C, but, data);
1360                         break;
1361                 case TRACKPREVIEW:
1362                         ui_apply_but_TRACKPREVIEW(C, but, data);
1363                         break;
1364                 default:
1365                         break;
1366         }
1367
1368         but->editstr = editstr;
1369         but->editval = editval;
1370         but->editvec = editvec;
1371         but->editcoba = editcoba;
1372         but->editcumap = editcumap;
1373 }
1374
1375 /* ******************* drop event ********************  */
1376
1377 /* only call if event type is EVT_DROP */
1378 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
1379 {
1380         wmDrag *wmd;
1381         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
1382         
1383         for (wmd = drags->first; wmd; wmd = wmd->next) {
1384                 if (wmd->type == WM_DRAG_ID) {
1385                         /* align these types with UI_but_active_drop_name */
1386                         if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1387                                 ID *id = (ID *)wmd->poin;
1388                                 
1389                                 if (but->poin == NULL && but->rnapoin.data == NULL) {}
1390                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1391                                 BLI_strncpy(data->str, id->name + 2, data->maxlen);
1392                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1393                         }
1394                 }
1395         }
1396         
1397 }
1398
1399 /* ******************* copy and paste ********************  */
1400
1401 /* c = copy, v = paste */
1402 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, char mode)
1403 {
1404         static ColorBand but_copypaste_coba = {0};
1405         char buf[UI_MAX_DRAW_STR + 1] = {0};
1406
1407         if (mode == 'v' && but->lock  == TRUE) {
1408                 return;
1409         }
1410
1411         if (mode == 'v') {
1412                 /* extract first line from clipboard in case of multi-line copies */
1413                 char *p, *pbuf = WM_clipboard_text_get(0);
1414                 p = pbuf;
1415                 if (p) {
1416                         int i = 0;
1417                         while (*p && *p != '\r' && *p != '\n' && i < UI_MAX_DRAW_STR) {
1418                                 buf[i++] = *p;
1419                                 p++;
1420                         }
1421                         buf[i] = 0;
1422                         MEM_freeN(pbuf);
1423                 }
1424         }
1425         
1426         /* numeric value */
1427         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
1428                 
1429                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1430                         /* pass */
1431                 }
1432                 else if (mode == 'c') {
1433                         /* Get many decimal places, then strip trailing zeros.
1434                          * note: too high values start to give strange results (6 or so is ok) */
1435                         ui_get_but_string_ex(but, buf, sizeof(buf), 6);
1436                         BLI_str_rstrip_float_zero(buf, '\0');
1437
1438                         WM_clipboard_text_set(buf, 0);
1439                 }
1440                 else {
1441                         double val;
1442
1443                         if (ui_set_but_string_eval_num(C, but, buf, &val)) {
1444                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1445                                 data->value = val;
1446                                 ui_set_but_string(C, but, buf);
1447                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1448                         }
1449                 }
1450         }
1451
1452         /* RGB triple */
1453         else if (but->type == COLOR) {
1454                 float rgba[4];
1455                 
1456                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1457                         /* pass */
1458                 }
1459                 else if (mode == 'c') {
1460                         if (RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1461                                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
1462                         else
1463                                 rgba[3] = 1.0f;
1464                         
1465                         ui_get_but_vectorf(but, rgba);
1466                         /* convert to linear color to do compatible copy between gamma and non-gamma */
1467                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1468                                 srgb_to_linearrgb_v3_v3(rgba, rgba);
1469
1470                         BLI_snprintf(buf, sizeof(buf), "[%f, %f, %f, %f]", rgba[0], rgba[1], rgba[2], rgba[3]);
1471                         WM_clipboard_text_set(buf, 0);
1472                         
1473                 }
1474                 else {
1475                         if (sscanf(buf, "[%f, %f, %f, %f]", &rgba[0], &rgba[1], &rgba[2], &rgba[3]) == 4) {
1476                                 /* assume linear colors in buffer */
1477                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1478                                         linearrgb_to_srgb_v3_v3(rgba, rgba);
1479
1480                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1481                                 ui_set_but_vectorf(but, rgba);
1482                                 if (RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1483                                         RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, rgba[3]);
1484
1485                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1486                         }
1487                 }
1488         }
1489
1490         /* text/string and ID data */
1491         else if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1492                 uiHandleButtonData *active_data = but->active;
1493
1494                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1495                         /* pass */
1496                 }
1497                 else if (mode == 'c') {
1498                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1499                         BLI_strncpy(buf, active_data->str, UI_MAX_DRAW_STR);
1500                         WM_clipboard_text_set(active_data->str, 0);
1501                         active_data->cancel = true;
1502                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1503                 }
1504                 else {
1505                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1506
1507                         if (ui_is_but_utf8(but)) BLI_strncpy_utf8(active_data->str, buf, active_data->maxlen);
1508                         else BLI_strncpy(active_data->str, buf, active_data->maxlen);
1509
1510                         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1511                                 /* else uiSearchboxData.active member is not updated [#26856] */
1512                                 ui_searchbox_update(C, data->searchbox, but, true);
1513                         }
1514                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1515                 }
1516         }
1517         /* colorband (not supported by system clipboard) */
1518         else if (but->type == BUT_COLORBAND) {
1519                 if (mode == 'c') {
1520                         if (but->poin == NULL)
1521                                 return;
1522
1523                         memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
1524                 }
1525                 else {
1526                         if (but_copypaste_coba.tot == 0)
1527                                 return;
1528
1529                         if (!but->poin)
1530                                 but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
1531
1532                         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1533                         memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
1534                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1535                 }
1536         }
1537         /* operator button (any type) */
1538         else if (but->optype) {
1539                 if (mode == 'c') {
1540                         PointerRNA *opptr;
1541                         char *str;
1542                         opptr = uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
1543
1544                         str = WM_operator_pystring(C, but->optype, opptr, 0);
1545
1546                         WM_clipboard_text_set(str, 0);
1547
1548                         MEM_freeN(str);
1549                 }
1550         }
1551 }
1552
1553 /* ************************ password text ******************************
1554  *
1555  * Functions to convert password strings that should not be displayed
1556  * to asterisk representation (e.g. mysecretpasswd -> *************)
1557  *
1558  * It converts every UTF-8 character to an asterisk, and also remaps
1559  * the cursor position and selection start/end.
1560  *
1561  * Note: remaping is used, because password could contain UTF-8 characters.
1562  *
1563  */
1564
1565 static int ui_text_position_from_hidden(uiBut *but, int pos)
1566 {
1567         const char *strpos;
1568         int i;
1569
1570         for (i = 0, strpos = but->drawstr; i < pos; i++)
1571                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
1572         
1573         return (strpos - but->drawstr);
1574 }
1575
1576 static int ui_text_position_to_hidden(uiBut *but, int pos)
1577 {
1578         return BLI_strnlen_utf8(but->drawstr, pos);
1579 }
1580
1581 void ui_button_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut *but, int restore)
1582 {
1583         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
1584                 return;
1585
1586         if (restore) {
1587                 /* restore original string */
1588                 BLI_strncpy(but->drawstr, password_str, UI_MAX_DRAW_STR);
1589
1590                 /* remap cursor positions */
1591                 if (but->pos >= 0) {
1592                         but->pos = ui_text_position_from_hidden(but, but->pos);
1593                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
1594                         but->selend = ui_text_position_from_hidden(but, but->selend);
1595                 }
1596         }
1597         else {
1598                 /* convert text to hidden test using asterisks (e.g. pass -> ****) */
1599                 int i, len = BLI_strlen_utf8(but->drawstr);
1600
1601                 /* remap cursor positions */
1602                 if (but->pos >= 0) {
1603                         but->pos = ui_text_position_to_hidden(but, but->pos);
1604                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
1605                         but->selend = ui_text_position_to_hidden(but, but->selend);
1606                 }
1607
1608                 /* save original string */
1609                 BLI_strncpy(password_str, but->drawstr, UI_MAX_DRAW_STR);
1610
1611                 for (i = 0; i < len; i++)
1612                         but->drawstr[i] = '*';
1613                 but->drawstr[i] = '\0';
1614         }
1615 }
1616
1617
1618 /* ************* in-button text selection/editing ************* */
1619
1620
1621 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
1622 {
1623         char *str = data->str;
1624         const int len = strlen(str);
1625         bool change = false;
1626         if (but->selsta != but->selend && len) {
1627                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
1628                 change = true;
1629         }
1630         
1631         but->pos = but->selend = but->selsta;
1632         return change;
1633 }
1634
1635 /* note, but->block->aspect is used here, when drawing button style is getting scaled too */
1636 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
1637 {
1638         uiStyle *style = UI_GetStyle();  // XXX pass on as arg
1639         uiFontStyle *fstyle = &style->widget;
1640         float startx = but->rect.xmin;
1641         char *origstr, password_str[UI_MAX_DRAW_STR];
1642
1643         uiStyleFontSet(fstyle);
1644
1645         if (fstyle->kerning == 1) /* for BLF_width */
1646                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1647         
1648         ui_button_text_password_hide(password_str, but, FALSE);
1649
1650         origstr = MEM_mallocN(sizeof(char) * data->maxlen, "ui_textedit origstr");
1651         
1652         BLI_strncpy(origstr, but->drawstr, data->maxlen);
1653         
1654         /* XXX solve generic, see: #widget_draw_text_icon */
1655         if (but->type == NUM || but->type == NUMSLI) {
1656                 startx += (int)(0.5f * (BLI_rctf_size_y(&but->rect)));
1657         }
1658         else if (ELEM3(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1659                 if (but->flag & UI_HAS_ICON) {
1660                         startx += UI_DPI_ICON_SIZE;
1661                 }
1662                 /* but this extra .05 makes clicks inbetween characters feel nicer */
1663                 startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit);
1664         }
1665         
1666         /* mouse dragged outside the widget to the left */
1667         if (x < startx) {
1668                 int i = but->ofs;
1669
1670                 origstr[but->ofs] = '\0';
1671                 
1672                 while (i > 0) {
1673                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &i)) {
1674                                 /* 0.25 == scale factor for less sensitivity */
1675                                 if (BLF_width(fstyle->uifont_id, origstr + i) > (startx - x) * 0.25f) {
1676                                         break;
1677                                 }
1678                         }
1679                         else {
1680                                 break; /* unlikely but possible */
1681                         }
1682                 }
1683                 but->ofs = i;
1684                 but->pos = but->ofs;
1685         }
1686         /* mouse inside the widget, mouse coords mapped in widget space */
1687         else {  /* (x >= startx) */
1688                 int pos_i;
1689
1690                 /* keep track of previous distance from the cursor to the char */
1691                 float cdist, cdist_prev = 0.0f;
1692                 short pos_prev;
1693                 
1694                 but->pos = pos_prev = strlen(origstr) - but->ofs;
1695
1696                 while (true) {
1697                         cdist = startx + BLF_width(fstyle->uifont_id, origstr + but->ofs);
1698
1699                         /* check if position is found */
1700                         if (cdist < x) {
1701                                 /* check is previous location was in fact closer */
1702                                 if (((float)x - cdist) > (cdist_prev - (float)x)) {
1703                                         but->pos = pos_prev;
1704                                 }
1705                                 break;
1706                         }
1707                         cdist_prev = cdist;
1708                         pos_prev   = but->pos;
1709                         /* done with tricky distance checks */
1710
1711                         pos_i = but->pos;
1712                         if (but->pos <= 0) break;
1713                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &pos_i)) {
1714                                 but->pos = pos_i;
1715                                 origstr[but->pos + but->ofs] = 0;
1716                         }
1717                         else {
1718                                 break; /* unlikely but possible */
1719                         }
1720                 }
1721                 but->pos += but->ofs;
1722                 if (but->pos < 0) but->pos = 0;
1723         }
1724         
1725         if (fstyle->kerning == 1)
1726                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1727         
1728         ui_button_text_password_hide(password_str, but, TRUE);
1729
1730         MEM_freeN(origstr);
1731 }
1732
1733 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
1734 {
1735         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
1736         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
1737
1738         ui_textedit_set_cursor_pos(but, data, x);
1739
1740         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
1741         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
1742
1743         ui_check_but(but);
1744 }
1745
1746 /* this is used for both utf8 and ascii, its meant to be used for single keys,
1747  * notice the buffer is either copied or not, so its not suitable for pasting in
1748  * - campbell */
1749 static bool ui_textedit_type_buf(uiBut *but, uiHandleButtonData *data,
1750                                  const char *utf8_buf, int utf8_buf_len)
1751 {
1752         char *str;
1753         int len;
1754         bool changed = false;
1755
1756         str = data->str;
1757         len = strlen(str);
1758
1759         if (len - (but->selend - but->selsta) + 1 <= data->maxlen) {
1760                 int step = utf8_buf_len;
1761
1762                 /* type over the current selection */
1763                 if ((but->selend - but->selsta) > 0) {
1764                         changed = ui_textedit_delete_selection(but, data);
1765                         len = strlen(str);
1766                 }
1767
1768                 if (len + step < data->maxlen) {
1769                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
1770                         memcpy(&str[but->pos], utf8_buf, step * sizeof(char));
1771                         but->pos += step;
1772                         changed = true;
1773                 }
1774         }
1775
1776         return changed;
1777 }
1778
1779 static bool ui_textedit_type_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
1780 {
1781         char buf[2] = {ascii, '\0'};
1782
1783         if (ui_is_but_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
1784                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
1785                        __func__, (int)(unsigned char)ascii);
1786
1787                 return false;
1788         }
1789
1790         /* in some cases we want to allow invalid utf8 chars */
1791         return ui_textedit_type_buf(but, data, buf, 1);
1792 }
1793
1794 static void ui_textedit_move(uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
1795                              int select, strCursorJumpType jump)
1796 {
1797         const char *str = data->str;
1798         const int len = strlen(str);
1799         const int pos_prev = but->pos;
1800         const int has_sel = (but->selend - but->selsta) > 0;
1801
1802         ui_check_but(but);
1803
1804         /* special case, quit selection and set cursor */
1805         if (has_sel && !select) {
1806                 if (jump == STRCUR_JUMP_ALL) {
1807                         but->selsta = but->selend = but->pos = direction ? len : 0;
1808                 }
1809                 else {
1810                         if (direction) {
1811                                 but->selsta = but->pos = but->selend;
1812                         }
1813                         else {
1814                                 but->pos = but->selend = but->selsta;
1815                         }
1816                 }
1817                 data->selextend = 0;
1818         }
1819         else {
1820                 int pos_i = but->pos;
1821                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
1822                 but->pos = pos_i;
1823
1824                 if (select) {
1825                         /* existing selection */
1826                         if (has_sel) {
1827
1828                                 if (data->selextend == 0) {
1829                                         data->selextend = EXTEND_RIGHT;
1830                                 }
1831
1832                                 if (direction) {
1833                                         if (data->selextend == EXTEND_RIGHT) {
1834                                                 but->selend = but->pos;
1835                                         }
1836                                         else {
1837                                                 but->selsta = but->pos;
1838                                         }
1839                                 }
1840                                 else {
1841                                         if (data->selextend == EXTEND_LEFT) {
1842                                                 but->selsta = but->pos;
1843                                         }
1844                                         else {
1845                                                 but->selend = but->pos;
1846                                         }
1847                                 }
1848
1849                                 if (but->selend < but->selsta) {
1850                                         SWAP(short, but->selsta, but->selend);
1851                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
1852                                 }
1853
1854                         } /* new selection */
1855                         else {
1856                                 if (direction) {
1857                                         data->selextend = EXTEND_RIGHT;
1858                                         but->selend = but->pos;
1859                                         but->selsta = pos_prev;
1860                                 }
1861                                 else {
1862                                         data->selextend = EXTEND_LEFT;
1863                                         but->selend = pos_prev;
1864                                         but->selsta = but->pos;
1865                                 }
1866                         }
1867                 }
1868         }
1869 }
1870
1871 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
1872 {
1873         char *str = data->str;
1874         const int len = strlen(str);
1875
1876         bool changed = false;
1877
1878         if (jump == STRCUR_JUMP_ALL) {
1879                 if (len) changed = true;
1880                 str[0] = '\0';
1881                 but->pos = 0;
1882         }
1883         else if (direction) { /* delete */
1884                 if ((but->selend - but->selsta) > 0) {
1885                         changed = ui_textedit_delete_selection(but, data);
1886                 }
1887                 else if (but->pos >= 0 && but->pos < len) {
1888                         int pos = but->pos;
1889                         int step;
1890                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
1891                         step = pos - but->pos;
1892                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - but->pos);
1893                         changed = true;
1894                 }
1895         }
1896         else { /* backspace */
1897                 if (len != 0) {
1898                         if ((but->selend - but->selsta) > 0) {
1899                                 changed = ui_textedit_delete_selection(but, data);
1900                         }
1901                         else if (but->pos > 0) {
1902                                 int pos = but->pos;
1903                                 int step;
1904
1905                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
1906                                 step = but->pos - pos;
1907                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
1908                                 but->pos -= step;
1909                                 changed = true;
1910                         }
1911                 }
1912         }
1913
1914         return changed;
1915 }
1916
1917 static bool ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
1918 {
1919         char *str;
1920         /* TODO, should return false if it cant autocomp. */
1921         bool changed = true;
1922
1923         str = data->str;
1924
1925         if (data->searchbox)
1926                 ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
1927         else
1928                 but->autocomplete_func(C, str, but->autofunc_arg);
1929
1930         but->pos = strlen(str);
1931         but->selsta = but->selend = but->pos;
1932
1933         return changed;
1934 }
1935
1936 /* mode for ui_textedit_copypaste() */
1937 enum {
1938         UI_TEXTEDIT_PASTE = 1,
1939         UI_TEXTEDIT_COPY,
1940         UI_TEXTEDIT_CUT
1941 };
1942
1943 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
1944 {
1945         char buf[UI_MAX_DRAW_STR] = {0};
1946         char *str, *p, *pbuf;
1947         int x;
1948         bool changed = false;
1949         int str_len, buf_len;
1950
1951         str = data->str;
1952         str_len = strlen(str);
1953         
1954         /* paste */
1955         if (mode == UI_TEXTEDIT_PASTE) {
1956                 /* TODO, ensure UTF8 ui_is_but_utf8() - campbell */
1957                 /* extract the first line from the clipboard */
1958                 p = pbuf = WM_clipboard_text_get(0);
1959
1960                 if (p && p[0]) {
1961                         unsigned int y;
1962                         buf_len = 0;
1963                         while (*p && *p != '\r' && *p != '\n' && buf_len < UI_MAX_DRAW_STR - 1) {
1964                                 buf[buf_len++] = *p;
1965                                 p++;
1966                         }
1967                         buf[buf_len] = 0;
1968
1969                         /* paste over the current selection */
1970                         if ((but->selend - but->selsta) > 0) {
1971                                 ui_textedit_delete_selection(but, data);
1972                                 str_len = strlen(str);
1973                         }
1974                         
1975                         for (y = 0; y < buf_len; y++) {
1976                                 /* add contents of buffer */
1977                                 if (str_len + 1 < data->maxlen) {
1978                                         for (x = data->maxlen; x > but->pos; x--)
1979                                                 str[x] = str[x - 1];
1980                                         str[but->pos] = buf[y];
1981                                         but->pos++; 
1982                                         str_len++;
1983                                         str[str_len] = '\0';
1984                                 }
1985                         }
1986
1987                         changed = true;
1988                 }
1989
1990                 if (pbuf) {
1991                         MEM_freeN(pbuf);
1992                 }
1993         }
1994         /* cut & copy */
1995         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
1996                 /* copy the contents to the copypaste buffer */
1997                 for (x = but->selsta; x <= but->selend; x++) {
1998                         if (x == but->selend)
1999                                 buf[x] = '\0';
2000                         else
2001                                 buf[(x - but->selsta)] = str[x];
2002                 }
2003
2004                 WM_clipboard_text_set(buf, 0);
2005                 
2006                 /* for cut only, delete the selection afterwards */
2007                 if (mode == UI_TEXTEDIT_CUT) {
2008                         if ((but->selend - but->selsta) > 0) {
2009                                 changed = ui_textedit_delete_selection(but, data);
2010                         }
2011                 }
2012         }
2013
2014         return changed;
2015 }
2016
2017 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2018 {
2019         int len;
2020
2021         if (data->str) {
2022                 MEM_freeN(data->str);
2023                 data->str = NULL;
2024         }
2025
2026         /* retrieve string */
2027         data->maxlen = ui_get_but_string_max_length(but);
2028         data->str = MEM_callocN(sizeof(char) * data->maxlen + 1, "textedit str");
2029         ui_get_but_string(but, data->str, data->maxlen);
2030
2031         if (ui_is_but_float(but) && !ui_is_but_unit(but)) {
2032                 BLI_str_rstrip_float_zero(data->str, '\0');
2033         }
2034
2035         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
2036                 ui_convert_to_unit_alt_name(but, data->str, data->maxlen);
2037         }
2038
2039         /* won't change from now on */
2040         len = strlen(data->str);
2041
2042         data->origstr = BLI_strdupn(data->str, len);
2043         data->selextend = 0;
2044         data->selstartx = 0;
2045
2046         /* set cursor pos to the end of the text */
2047         but->editstr = data->str;
2048         but->pos = len;
2049         but->selsta = 0;
2050         but->selend = len;
2051
2052         /* optional searchbox */
2053         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2054                 data->searchbox = ui_searchbox_create(C, data->region, but);
2055                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
2056         }
2057
2058         /* reset alert flag (avoid confusion, will refresh on exit) */
2059         but->flag &= ~UI_BUT_REDALERT;
2060
2061         ui_check_but(but);
2062         
2063         WM_cursor_modal(CTX_wm_window(C), BC_TEXTEDITCURSOR);
2064 }
2065
2066 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2067 {
2068         if (but) {
2069                 if (ui_is_but_utf8(but)) {
2070                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
2071                         /* not a file?, strip non utf-8 chars */
2072                         if (strip) {
2073                                 /* wont happen often so isn't that annoying to keep it here for a while */
2074                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
2075                         }
2076                 }
2077                 
2078                 if (data->searchbox) {
2079                         if (data->cancel == false) {
2080                                 if ((ui_searchbox_apply(but, data->searchbox) == false) &&
2081                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
2082                                 {
2083                                         data->cancel = true;
2084                                 }
2085                         }
2086
2087                         ui_searchbox_free(C, data->searchbox);
2088                         data->searchbox = NULL;
2089                 }
2090                 
2091                 but->editstr = NULL;
2092                 but->pos = -1;
2093         }
2094         
2095         WM_cursor_restore(CTX_wm_window(C));
2096 }
2097
2098 static void ui_textedit_next_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2099 {
2100         uiBut *but;
2101
2102         /* label and roundbox can overlap real buttons (backdrops...) */
2103         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
2104                 return;
2105
2106         for (but = actbut->next; but; but = but->next) {
2107                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2108                         if (!(but->flag & UI_BUT_DISABLED)) {
2109                                 data->postbut = but;
2110                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2111                                 return;
2112                         }
2113                 }
2114         }
2115         for (but = block->buttons.first; but != actbut; but = but->next) {
2116                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2117                         if (!(but->flag & UI_BUT_DISABLED)) {
2118                                 data->postbut = but;
2119                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2120                                 return;
2121                         }
2122                 }
2123         }
2124 }
2125
2126 static void ui_textedit_prev_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2127 {
2128         uiBut *but;
2129
2130         /* label and roundbox can overlap real buttons (backdrops...) */
2131         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
2132                 return;
2133
2134         for (but = actbut->prev; but; but = but->prev) {
2135                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2136                         if (!(but->flag & UI_BUT_DISABLED)) {
2137                                 data->postbut = but;
2138                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2139                                 return;
2140                         }
2141                 }
2142         }
2143         for (but = block->buttons.last; but != actbut; but = but->prev) {
2144                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2145                         if (!(but->flag & UI_BUT_DISABLED)) {
2146                                 data->postbut = but;
2147                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2148                                 return;
2149                         }
2150                 }
2151         }
2152 }
2153
2154
2155 static void ui_do_but_textedit(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2156 {
2157         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2158         bool changed = false, inbox = false, update = false;
2159
2160         switch (event->type) {
2161                 case MOUSEMOVE:
2162                 case MOUSEPAN:
2163                         if (data->searchbox) {
2164 #ifdef USE_KEYNAV_LIMIT
2165                                 if ((event->type == MOUSEMOVE) && ui_mouse_motion_keynav_test(&data->searchbox_keynav_state, event)) {
2166                                         /* pass */
2167                                 }
2168                                 else {
2169                                         ui_searchbox_event(C, data->searchbox, but, event);
2170                                 }
2171 #else
2172                                 ui_searchbox_event(C, data->searchbox, but, event);
2173 #endif
2174                         }
2175                         
2176                         break;
2177                 case RIGHTMOUSE:
2178                 case ESCKEY:
2179                         data->cancel = true;
2180                         data->escapecancel = true;
2181                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2182                         retval = WM_UI_HANDLER_BREAK;
2183                         break;
2184                 case LEFTMOUSE:
2185                 {
2186                         /* exit on LMB only on RELEASE for searchbox, to mimic other popups, and allow multiple menu levels */
2187                         if (data->searchbox)
2188                                 inbox = ui_searchbox_inside(data->searchbox, event->x, event->y);
2189
2190                         if (event->val == KM_PRESS) {
2191                                 mx = event->x;
2192                                 my = event->y;
2193                                 ui_window_to_block(data->region, block, &mx, &my);
2194
2195                                 if (ui_but_contains_pt(but, mx, my)) {
2196                                         ui_textedit_set_cursor_pos(but, data, mx);
2197                                         but->selsta = but->selend = but->pos;
2198                                         data->selstartx = mx;
2199
2200                                         button_activate_state(C, but, BUTTON_STATE_TEXT_SELECTING);
2201                                         retval = WM_UI_HANDLER_BREAK;
2202                                 }
2203                                 else if (inbox == false) {
2204                                         /* if searchbox, click outside will cancel */
2205                                         if (data->searchbox)
2206                                                 data->cancel = data->escapecancel = true;
2207                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2208                                         retval = WM_UI_HANDLER_BREAK;
2209                                 }
2210                         }
2211                         else if (inbox) {
2212                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2213                                 retval = WM_UI_HANDLER_BREAK;
2214                         }
2215                         break;
2216                 }
2217         }
2218
2219         if (event->val == KM_PRESS) {
2220                 switch (event->type) {
2221                         case VKEY:
2222                         case XKEY:
2223                         case CKEY:
2224                                 if (event->ctrl || event->oskey) {
2225                                         if (event->type == VKEY)
2226                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_PASTE);
2227                                         else if (event->type == CKEY)
2228                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_COPY);
2229                                         else if (event->type == XKEY)
2230                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_CUT);
2231
2232                                         retval = WM_UI_HANDLER_BREAK;
2233                                 }
2234                                 break;
2235                         case RIGHTARROWKEY:
2236                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2237                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2238                                 retval = WM_UI_HANDLER_BREAK;
2239                                 break;
2240                         case LEFTARROWKEY:
2241                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2242                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2243                                 retval = WM_UI_HANDLER_BREAK;
2244                                 break;
2245                         case WHEELDOWNMOUSE:
2246                         case DOWNARROWKEY:
2247                                 if (data->searchbox) {
2248 #ifdef USE_KEYNAV_LIMIT
2249                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2250 #endif
2251                                         ui_searchbox_event(C, data->searchbox, but, event);
2252                                         break;
2253                                 }
2254                         /* pass on purposedly */
2255                         case ENDKEY:
2256                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2257                                                  event->shift, STRCUR_JUMP_ALL);
2258                                 retval = WM_UI_HANDLER_BREAK;
2259                                 break;
2260                         case WHEELUPMOUSE:
2261                         case UPARROWKEY:
2262                                 if (data->searchbox) {
2263 #ifdef USE_KEYNAV_LIMIT
2264                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2265 #endif
2266                                         ui_searchbox_event(C, data->searchbox, but, event);
2267                                         break;
2268                                 }
2269                         /* pass on purposedly */
2270                         case HOMEKEY:
2271                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2272                                                  event->shift, STRCUR_JUMP_ALL);
2273                                 retval = WM_UI_HANDLER_BREAK;
2274                                 break;
2275                         case PADENTER:
2276                         case RETKEY:
2277                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2278                                 retval = WM_UI_HANDLER_BREAK;
2279                                 break;
2280                         case DELKEY:
2281                                 changed = ui_textedit_delete(but, data, 1,
2282                                                              event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2283                                 retval = WM_UI_HANDLER_BREAK;
2284                                 break;
2285
2286                         case BACKSPACEKEY:
2287                                 changed = ui_textedit_delete(but, data, 0,
2288                                                              event->shift ? STRCUR_JUMP_ALL : (event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE));
2289                                 retval = WM_UI_HANDLER_BREAK;
2290                                 break;
2291                                 
2292                         case AKEY:
2293                                 /* Ctrl + A: Select all */
2294                                 if (event->ctrl && !(event->alt || event->shift || event->oskey)) {
2295                                         ui_textedit_move(but, data, STRCUR_DIR_PREV,
2296                                                          false, STRCUR_JUMP_ALL);
2297                                         ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2298                                                          true, STRCUR_JUMP_ALL);
2299                                         retval = WM_UI_HANDLER_BREAK;
2300                                 }
2301                                 break;
2302
2303                         case TABKEY:
2304                                 /* there is a key conflict here, we can't tab with autocomplete */
2305                                 if (but->autocomplete_func || data->searchbox) {
2306                                         changed = ui_textedit_autocomplete(C, but, data);
2307                                         update = true;  /* do live update for tab key */
2308                                 }
2309                                 /* the hotkey here is not well defined, was G.qual so we check all */
2310                                 else if (event->shift || event->ctrl || event->alt || event->oskey) {
2311                                         ui_textedit_prev_but(block, but, data);
2312                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2313                                 }
2314                                 else {
2315                                         ui_textedit_next_but(block, but, data);
2316                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2317                                 }
2318                                 retval = WM_UI_HANDLER_BREAK;
2319                                 break;
2320                 }
2321
2322                 if ((event->ascii || event->utf8_buf[0]) && (retval == WM_UI_HANDLER_CONTINUE)) {
2323                         char ascii = event->ascii;
2324                         const char *utf8_buf = event->utf8_buf;
2325
2326                         /* exception that's useful for number buttons, some keyboard
2327                          * numpads have a comma instead of a period */
2328                         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) { /* could use data->min*/
2329                                 if (event->type == PADPERIOD && ascii == ',') {
2330                                         ascii = '.';
2331                                         utf8_buf = NULL; /* force ascii fallback */
2332                                 }
2333                         }
2334
2335                         if (utf8_buf && utf8_buf[0]) {
2336                                 int utf8_buf_len = BLI_str_utf8_size(utf8_buf);
2337                                 /* keep this printf until utf8 is well tested */
2338                                 if (utf8_buf_len != 1) {
2339                                         printf("%s: utf8 char '%.*s'\n", __func__, utf8_buf_len, utf8_buf);
2340                                 }
2341
2342                                 // strcpy(utf8_buf, "12345");
2343                                 changed = ui_textedit_type_buf(but, data, event->utf8_buf, utf8_buf_len);
2344                         }
2345                         else {
2346                                 changed = ui_textedit_type_ascii(but, data, ascii);
2347                         }
2348
2349                         retval = WM_UI_HANDLER_BREAK;
2350                         
2351                 }
2352                 /* textbutton with magnifier icon: do live update for search button */
2353                 if (but->icon == ICON_VIEWZOOM)
2354                         update = true;
2355         }
2356
2357         if (changed) {
2358                 /* only update when typing for TAB key */
2359                 if (update && data->interactive) {
2360                         ui_apply_button(C, block, but, data, true);
2361                 }
2362                 else {
2363                         ui_check_but(but);
2364                 }
2365                 but->changed = true;
2366                 
2367                 if (data->searchbox)
2368                         ui_searchbox_update(C, data->searchbox, but, true);  /* true = reset */
2369         }
2370
2371         if (changed || (retval == WM_UI_HANDLER_BREAK))
2372                 ED_region_tag_redraw(data->region);
2373 }
2374
2375 static void ui_do_but_textedit_select(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2376 {
2377         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2378
2379         switch (event->type) {
2380                 case MOUSEMOVE:
2381                 {
2382                         mx = event->x;
2383                         my = event->y;
2384                         ui_window_to_block(data->region, block, &mx, &my);
2385
2386                         ui_textedit_set_cursor_select(but, data, mx);
2387                         retval = WM_UI_HANDLER_BREAK;
2388                         break;
2389                 }
2390                 case LEFTMOUSE:
2391                         if (event->val == KM_RELEASE)
2392                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2393                         retval = WM_UI_HANDLER_BREAK;
2394                         break;
2395         }
2396
2397         if (retval == WM_UI_HANDLER_BREAK) {
2398                 ui_check_but(but);
2399                 ED_region_tag_redraw(data->region);
2400         }
2401 }
2402
2403 /* ************* number editing for various types ************* */
2404
2405 static void ui_numedit_begin(uiBut *but, uiHandleButtonData *data)
2406 {
2407         if (but->type == BUT_CURVE) {
2408                 but->editcumap = (CurveMapping *)but->poin;
2409         }
2410         else if (but->type == BUT_COLORBAND) {
2411                 data->coba = (ColorBand *)but->poin;
2412                 but->editcoba = data->coba;
2413         }
2414         else if (ELEM4(but->type, BUT_NORMAL, HSVCUBE, HSVCIRCLE, COLOR)) {
2415                 ui_get_but_vectorf(but, data->origvec);
2416                 copy_v3_v3(data->vec, data->origvec);
2417                 but->editvec = data->vec;
2418         }
2419         else {
2420                 float softrange, softmin, softmax;
2421
2422                 data->startvalue = ui_get_but_val(but);
2423                 data->origvalue = data->startvalue;
2424                 data->value = data->origvalue;
2425                 but->editval = &data->value;
2426
2427                 softmin = but->softmin;
2428                 softmax = but->softmax;
2429                 softrange = softmax - softmin;
2430
2431                 data->dragfstart = (softrange == 0.0f) ? 0.0f : ((float)data->value - softmin) / softrange;
2432                 data->dragf = data->dragfstart;
2433         }
2434
2435         data->dragchange = false;
2436         data->draglock = true;
2437 }
2438
2439 static void ui_numedit_end(uiBut *but, uiHandleButtonData *data)
2440 {
2441         but->editval = NULL;
2442         but->editvec = NULL;
2443         but->editcoba = NULL;
2444         but->editcumap = NULL;
2445
2446         data->dragstartx = 0;
2447         data->draglastx = 0;
2448         data->dragchange = false;
2449         data->dragcbd = NULL;
2450         data->dragsel = 0;
2451 }
2452
2453 static void ui_numedit_apply(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
2454 {
2455         if (data->interactive) {
2456                 ui_apply_button(C, block, but, data, true);
2457         }
2458         else {
2459                 ui_check_but(but);
2460         }
2461
2462         ED_region_tag_redraw(data->region);
2463 }
2464
2465 /* ****************** menu opening for various types **************** */
2466
2467 static void ui_blockopen_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2468 {
2469         uiBlockCreateFunc func = NULL;
2470         uiBlockHandleCreateFunc handlefunc = NULL;
2471         uiMenuCreateFunc menufunc = NULL;
2472         char *menustr = NULL;
2473         void *arg = NULL;
2474
2475         switch (but->type) {
2476                 case BLOCK:
2477                 case PULLDOWN:
2478                         if (but->menu_create_func) {
2479                                 menufunc = but->menu_create_func;
2480                                 arg = but->poin;
2481                         }
2482                         else {
2483                                 func = but->block_create_func;
2484                                 arg = but->poin ? but->poin : but->func_argN;
2485                         }
2486                         break;
2487                 case MENU:
2488                         if (but->menu_create_func) {
2489                                 menufunc = but->menu_create_func;
2490                                 arg = but->poin;
2491                         }
2492                         else {
2493                                 data->origvalue = ui_get_but_val(but);
2494                                 data->value = data->origvalue;
2495                                 but->editval = &data->value;
2496
2497                                 menustr = but->str;
2498                         }
2499                         break;
2500                 case ICONROW:
2501                         menufunc = ui_block_func_ICONROW;
2502                         arg = but;
2503                         break;
2504                 case ICONTEXTROW:
2505                         menufunc = ui_block_func_ICONTEXTROW;
2506                         arg = but;
2507                         break;
2508                 case COLOR:
2509                         ui_get_but_vectorf(but, data->origvec);
2510                         copy_v3_v3(data->vec, data->origvec);
2511                         but->editvec = data->vec;
2512
2513                         handlefunc = ui_block_func_COLOR;
2514                         arg = but;
2515                         break;
2516
2517                         /* quiet warnings for unhandled types */
2518                 default:
2519                         break;
2520         }
2521
2522         if (func || handlefunc) {
2523                 data->menu = ui_popup_block_create(C, data->region, but, func, handlefunc, arg);
2524                 if (but->block->handle)
2525                         data->menu->popup = but->block->handle->popup;
2526         }
2527         else if (menufunc || menustr) {
2528                 data->menu = ui_popup_menu_create(C, data->region, but, menufunc, arg, menustr);
2529                 if (but->block->handle)
2530                         data->menu->popup = but->block->handle->popup;
2531         }
2532
2533         /* this makes adjacent blocks auto open from now on */
2534         //if (but->block->auto_open == 0) but->block->auto_open = 1;
2535 }
2536
2537 static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2538 {
2539         if (but) {
2540                 but->editval = NULL;
2541                 but->editvec = NULL;
2542
2543                 but->block->auto_open_last = PIL_check_seconds_timer();
2544         }
2545
2546         if (data->menu) {
2547                 ui_popup_block_free(C, data->menu);
2548                 data->menu = NULL;
2549         }
2550 }
2551
2552 int ui_button_open_menu_direction(uiBut *but)
2553 {
2554         uiHandleButtonData *data = but->active;
2555
2556         if (data && data->menu)
2557                 return data->menu->direction;
2558         
2559         return 0;
2560 }
2561
2562 /* ***************** events for different button types *************** */
2563
2564 static int ui_do_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2565 {
2566         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2567                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2568                         button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE);
2569                         return WM_UI_HANDLER_BREAK;
2570                 }
2571                 else if (event->type == LEFTMOUSE && but->block->handle) {
2572                         /* regular buttons will be 'UI_SELECT', menu items 'UI_ACTIVE' */
2573                         if (!(but->flag & (UI_SELECT | UI_ACTIVE)))
2574                                 data->cancel = true;
2575                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2576                         return WM_UI_HANDLER_BREAK;
2577                 }
2578                 else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
2579                         button_activate_state(C, but, BUTTON_STATE_WAIT_FLASH);
2580                         return WM_UI_HANDLER_BREAK;
2581                 }
2582         }
2583         else if (data->state == BUTTON_STATE_WAIT_RELEASE) {
2584                 if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
2585                         if (!(but->flag & UI_SELECT))
2586                                 data->cancel = true;
2587                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2588                         return WM_UI_HANDLER_BREAK;
2589                 }
2590         }
2591
2592         return WM_UI_HANDLER_CONTINUE;
2593 }
2594
2595 static int ui_do_but_HOTKEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2596 {
2597         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2598                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2599                         but->drawstr[0] = 0;
2600                         but->modifier_key = 0;
2601                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2602                         return WM_UI_HANDLER_BREAK;
2603                 }
2604         }
2605         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2606                 
2607                 if (event->type == MOUSEMOVE)
2608                         return WM_UI_HANDLER_CONTINUE;
2609                 
2610                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2611                         /* only cancel if click outside the button */
2612                         if (ui_mouse_inside_button(but->active->region, but, event->x, event->y) == 0) {
2613                                 /* data->cancel doesnt work, this button opens immediate */
2614                                 if (but->flag & UI_BUT_IMMEDIATE)
2615                                         ui_set_but_val(but, 0);
2616                                 else
2617                                         data->cancel = true;
2618                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2619                                 return WM_UI_HANDLER_BREAK;
2620                         }
2621                 }
2622                 
2623                 /* always set */
2624                 but->modifier_key = 0;
2625                 if (event->shift) but->modifier_key |= KM_SHIFT;
2626                 if (event->alt) but->modifier_key |= KM_ALT;
2627                 if (event->ctrl) but->modifier_key |= KM_CTRL;
2628                 if (event->oskey) but->modifier_key |= KM_OSKEY;
2629
2630                 ui_check_but(but);
2631                 ED_region_tag_redraw(data->region);
2632                         
2633                 if (event->val == KM_PRESS) {
2634                         if (ISHOTKEY(event->type)) {
2635                                 
2636                                 if (WM_key_event_string(event->type)[0])
2637                                         ui_set_but_val(but, event->type);
2638                                 else
2639                                         data->cancel = true;
2640                                 
2641                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2642                                 return WM_UI_HANDLER_BREAK;
2643                         }
2644                         else if (event->type == ESCKEY) {
2645                                 data->cancel = true;
2646                                 data->escapecancel = true;
2647                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2648                         }
2649                         
2650                 }
2651         }
2652         
2653         return WM_UI_HANDLER_CONTINUE;
2654 }
2655
2656 static int ui_do_but_KEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2657 {
2658         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2659                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2660                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2661                         return WM_UI_HANDLER_BREAK;
2662                 }
2663         }
2664         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2665                 if (event->type == MOUSEMOVE)
2666                         return WM_UI_HANDLER_CONTINUE;
2667
2668                 if (event->val == KM_PRESS) {
2669                         if (WM_key_event_string(event->type)[0])
2670                                 ui_set_but_val(but, event->type);
2671                         else
2672                                 data->cancel = true;
2673
2674                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2675                 }
2676         }
2677
2678         return WM_UI_HANDLER_CONTINUE;
2679 }
2680
2681 static int ui_do_but_TEX(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2682 {
2683         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2684                 if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2685                         if (but->dt == UI_EMBOSSN && !event->ctrl) {
2686                                 /* pass */
2687                         }
2688                         else {
2689                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2690                                 return WM_UI_HANDLER_BREAK;
2691                         }
2692                 }
2693         }
2694         else if (data->state == BUTTON_STATE_TEXT_EDITING) {
2695                 ui_do_but_textedit(C, block, but, data, event);
2696                 return WM_UI_HANDLER_BREAK;
2697         }
2698         else if (data->state == BUTTON_STATE_TEXT_SELECTING) {
2699                 ui_do_but_textedit_select(C, block, but, data, event);
2700                 return WM_UI_HANDLER_BREAK;
2701         }
2702
2703         return WM_UI_HANDLER_CONTINUE;
2704 }
2705
2706 static int ui_do_but_SEARCH_UNLINK(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2707 {
2708         /* unlink icon is on right */
2709         if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2710                 ARegion *ar = data->region;
2711                 rcti rect;
2712                 int x = event->x, y = event->y;
2713                 
2714                 ui_window_to_block(ar, but->block, &x, &y);
2715                 
2716                 BLI_rcti_rctf_copy(&rect, &but->rect);
2717                 
2718                 rect.xmin = rect.xmax - (BLI_rcti_size_y(&rect));
2719                 if ( BLI_rcti_isect_pt(&rect, x, y) ) {
2720                         /* most likely NULL, but let's check, and give it temp zero string */
2721                         if (data->str == NULL)
2722                                 data->str = MEM_callocN(16, "temp str");
2723                         data->str[0] = 0;
2724                         
2725                         ui_apply_but_TEX(C, but, data);
2726                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2727                         
2728                         return WM_UI_HANDLER_BREAK;
2729                 }
2730         }
2731         return ui_do_but_TEX(C, block, but, data, event);
2732 }
2733
2734 static int ui_do_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2735 {
2736 #ifdef USE_DRAG_TOGGLE
2737         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2738                 if (event->type == LEFTMOUSE && event->val == KM_PRESS && ui_is_but_bool(but)) {
2739                         data->togdual = event->ctrl;
2740                         data->togonly = !event->shift;
2741                         ui_apply_button(C, but->block, but, data, true);
2742                         button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2743                         data->dragstartx = event->x;
2744                         data->dragstarty = event->y;
2745                         return WM_UI_HANDLER_BREAK;
2746                 }
2747         }
2748         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2749                 /* note: the 'BUTTON_STATE_WAIT_DRAG' part of 'ui_do_but_EXIT' could be refactored into its own function */
2750                 data->applied = false;
2751                 return ui_do_but_EXIT(C, but, data, event);
2752         }
2753 #endif
2754         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2755                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2756                         data->togdual = event->ctrl;
2757                         data->togonly = !event->shift;
2758                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2759                         return WM_UI_HANDLER_BREAK;
2760                 }
2761         }
2762         return WM_UI_HANDLER_CONTINUE;
2763 }
2764
2765 static int ui_do_but_EXIT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2766 {
2767         
2768         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2769
2770                 /* first handle click on icondrag type button */
2771                 if (event->type == LEFTMOUSE && but->dragpoin) {
2772                         if (ui_but_mouse_inside_icon(but, data->region, event)) {
2773                                 
2774                                 /* tell the button to wait and keep checking further events to
2775                                  * see if it should start dragging */
2776                                 button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2777                                 data->dragstartx = event->x;
2778                                 data->dragstarty = event->y;
2779                                 return WM_UI_HANDLER_CONTINUE;
2780                         }
2781                 }
2782 #ifdef USE_DRAG_TOGGLE
2783                 if (event->type == LEFTMOUSE && ui_is_but_bool(but)) {
2784                         button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2785                         data->dragstartx = event->x;
2786                         data->dragstarty = event->y;
2787                         return WM_UI_HANDLER_CONTINUE;
2788                 }
2789 #endif
2790
2791                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2792                         int ret = WM_UI_HANDLER_BREAK;
2793                         /* XXX (a bit ugly) Special case handling for filebrowser drag button */
2794                         if (but->dragpoin && but->imb && ui_but_mouse_inside_icon(but, data->region, event)) {
2795                                 ret = WM_UI_HANDLER_CONTINUE;
2796                         }
2797                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2798                         return ret;
2799                 }
2800         }
2801         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2802                 
2803                 /* this function also ends state */
2804                 if (ui_but_start_drag(C, but, data, event)) {
2805                         return WM_UI_HANDLER_BREAK;
2806                 }
2807                 
2808                 /* If the mouse has been pressed and released, getting to 
2809                  * this point without triggering a drag, then clear the 
2810                  * drag state for this button and continue to pass on the event */
2811                 if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2812                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2813                         return WM_UI_HANDLER_CONTINUE;
2814                 }
2815                 
2816                 /* while waiting for a drag to be triggered, always block 
2817                  * other events from getting handled */
2818                 return WM_UI_HANDLER_BREAK;
2819         }
2820         
2821         return WM_UI_HANDLER_CONTINUE;
2822 }
2823
2824 /* var names match ui_numedit_but_NUM */
2825 static float ui_numedit_apply_snapf(uiBut *but, float tempf, float softmin, float softmax, float softrange, int snap)
2826 {
2827         if (tempf == softmin || tempf == softmax || snap == 0) {
2828                 /* pass */
2829         }
2830         else {
2831                 float fac = 1.0f;
2832                 
2833                 if (ui_is_but_unit(but)) {
2834                         UnitSettings *unit = but->block->unit;
2835                         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
2836
2837                         if (bUnit_IsValid(unit->system, unit_type)) {
2838                                 fac = (float)bUnit_BaseScalar(unit->system, unit_type);
2839                                 if (ELEM3(unit_type, B_UNIT_LENGTH, B_UNIT_AREA, B_UNIT_VOLUME)) {
2840                                         fac /= unit->scale_length;
2841                                 }
2842                         }
2843                 }
2844
2845                 if (fac != 1.0f) {
2846                         /* snap in unit-space */
2847                         tempf /= fac;
2848                         /* softmin /= fac; */ /* UNUSED */
2849                         /* softmax /= fac; */ /* UNUSED */
2850                         softrange /= fac;
2851                 }
2852
2853                 if (snap == 1) {
2854                         if      (softrange < 2.10f) tempf = 0.1f  * floorf(10.0f * tempf);
2855                         else if (softrange < 21.0f) tempf = floorf(tempf);
2856                         else                        tempf = 10.0f * floorf(tempf / 10.0f);
2857                 }
2858                 else if (snap == 2) {
2859                         if      (softrange < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
2860                         else if (softrange < 21.0f) tempf = 0.1f  * floorf(10.0f * tempf);
2861                         else                        tempf = floor(tempf);
2862                 }
2863                 
2864                 if (fac != 1.0f)
2865                         tempf *= fac;
2866         }
2867
2868         return tempf;
2869 }
2870
2871 static float ui_numedit_apply_snap(int temp, float softmin, float softmax, int snap)
2872 {
2873         if (temp == softmin || temp == softmax)
2874                 return temp;
2875
2876         switch (snap) {
2877                 case 0:
2878                         break;
2879                 case 1:
2880                         temp = 10 * (temp / 10);
2881                         break;
2882                 case 2:
2883                         temp = 100 * (temp / 100);
2884                         break;
2885         }
2886
2887         return temp;
2888 }
2889
2890 static bool ui_numedit_but_NUM(uiBut *but, uiHandleButtonData *data, float fac, int snap, int mx)
2891 {
2892         float deler, tempf, softmin, softmax, softrange;
2893         int lvalue, temp;
2894         bool changed = false;
2895         const bool is_float = ui_is_but_float(but);
2896         
2897         if (mx == data->draglastx)
2898                 return changed;
2899         
2900         /* drag-lock - prevent unwanted scroll adjustments */
2901         /* change value (now 3) to adjust threshold in pixels */
2902         if (data->draglock) {
2903                 if (abs(mx - data->dragstartx) <= 3)
2904                         return changed;
2905
2906                 data->draglock = false;
2907                 data->dragstartx = mx;  /* ignore mouse movement within drag-lock */
2908         }
2909
2910         softmin = but->softmin;
2911         softmax = but->softmax;
2912         softrange = softmax - softmin;
2913
2914         if (ui_is_a_warp_but(but)) {
2915                 /* Mouse location isn't screen clamped to the screen so use a linear mapping
2916                  * 2px == 1-int, or 1px == 1-ClickStep */
2917                 if (is_float) {
2918                         fac *= 0.01f * but->a1;
2919                         tempf = (float)data->startvalue + ((float)(mx - data->dragstartx) * fac);
2920                         tempf = ui_numedit_apply_snapf(but, tempf, softmin, softmax, softrange, snap);
2921
2922 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2923                         if (tempf < softmin) {
2924                                 data->dragstartx -= (softmin - tempf) / fac;
2925                                 tempf = softmin;
2926                         }
2927                         else if (tempf > softmax) {
2928                                 data->dragstartx += (tempf - softmax) / fac;
2929                                 tempf = softmax;
2930                         }
2931 #else
2932                         CLAMP(tempf, softmin, softmax);
2933 #endif
2934
2935                         if (tempf != (float)data->value) {
2936                                 data->dragchange = true;
2937                                 data->value = tempf;
2938                                 changed = true;
2939                         }
2940                 }
2941                 else {
2942                         if      (softrange > 256) fac = 1.0;        /* 1px == 1 */
2943                         else if (softrange >  32) fac = 1.0 / 2.0;  /* 2px == 1 */
2944                         else                      fac = 1.0 / 16.0; /* 16px == 1? */
2945
2946                         temp = data->startvalue + (((double)mx - data->dragstartx) * (double)fac);
2947                         temp = ui_numedit_apply_snap(temp, softmin, softmax, snap);
2948
2949 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2950                         if (temp < softmin) {
2951                                 data->dragstartx -= (softmin - temp) / fac;
2952                                 temp = softmin;
2953                         }
2954                         else if (temp > softmax) {
2955                                 data->dragstartx += (temp - softmax) / fac;
2956                                 temp = softmax;
2957                         }
2958 #else
2959                         CLAMP(temp, softmin, softmax);
2960 #endif
2961
2962                         if (temp != data->value) {
2963                                 data->dragchange = true;
2964                                 data->value = temp;
2965                                 changed = true;
2966                         }
2967                 }
2968
2969                 data->draglastx = mx;
2970         }
2971         else {
2972                 /* Use a non-linear mapping of the mouse drag especially for large floats (normal behavior) */
2973                 deler = 500;
2974                 if (!is_float) {
2975                         /* prevent large ranges from getting too out of control */
2976                         if      (softrange > 600) deler = powf(softrange, 0.75f);
2977                         else if (softrange <  25) deler = 50.0;
2978                         else if (softrange < 100) deler = 100.0;
2979                 }
2980                 deler /= fac;
2981
2982                 if ((is_float == true) && (softrange > 11)) {
2983                         /* non linear change in mouse input- good for high precicsion */
2984                         data->dragf += (((float)(mx - data->draglastx)) / deler) * (fabsf(mx - data->dragstartx) / 500.0f);
2985                 }
2986                 else if ((is_float == false) && (softrange > 129)) { /* only scale large int buttons */
2987                         /* non linear change in mouse input- good for high precicsionm ints need less fine tuning */
2988                         data->dragf += (((float)(mx - data->draglastx)) / deler) * (fabsf(mx - data->dragstartx) / 250.0f);
2989                 }
2990                 else {
2991                         /*no sca