fix for mistake in own commit r56399, it broke click-dragging to open and select...
[blender-staging.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_set;
760         float but_cent_start[2];
761         eButType but_type_start;
762
763         bool xy_lock[2];
764         int  xy_last[2];
765 } uiDragToggleHandle;
766
767 static bool ui_drag_toggle_set_xy_xy(bContext *C, ARegion *ar, const bool is_set, const eButType but_type_start,
768                                      const int xy_src[2], const int xy_dst[2])
769 {
770         bool change = false;
771         uiBlock *block;
772
773         for (block = ar->uiblocks.first; block; block = block->next) {
774                 uiBut *but;
775
776                 float xy_a_block[2] = {UNPACK2(xy_src)};
777                 float xy_b_block[2] = {UNPACK2(xy_dst)};
778
779                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
780                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
781
782                 for (but = block->buttons.first; but; but = but->next) {
783                         if (ui_is_but_interactive(but)) {
784                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
785
786                                         /* execute the button */
787                                         if (ui_is_but_bool(but) && but->type == but_type_start) {
788                                                 /* is it pressed? */
789                                                 bool is_set_but = ui_is_but_push(but);
790                                                 BLI_assert(ui_is_but_bool(but) == true);
791                                                 if (is_set_but != is_set) {
792                                                         uiButExecute(C, but);
793                                                         change = true;
794                                                 }
795                                         }
796                                         /* done */
797
798                                 }
799                         }
800                 }
801         }
802
803         return change;
804 }
805
806 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
807 {
808         ARegion *ar = CTX_wm_region(C);
809         bool do_draw = false;
810         int xy[2];
811
812         /**
813          * Initialize Locking:
814          *
815          * Check if we need to initialize the lock axis by finding if the first
816          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
817          */
818         if (drag_info->xy_lock[0] == false && drag_info->xy_lock[1] == false) {
819                 /* first store the buttons original coords */
820                 uiBut *but = ui_but_find_mouse_over(ar, xy_input[0], xy_input[1]);
821                 if (but) {
822                         const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect),
823                                                        BLI_rctf_cent_y(&but->rect)};
824
825                         /* check if this is a different button, chances are high the button wont move about :) */
826                         if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
827                                 if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
828                                     fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
829                                 {
830                                         drag_info->xy_lock[0] = true;
831                                 }
832                                 else {
833                                         drag_info->xy_lock[1] = true;
834                                 }
835                         }
836                 }
837         }
838         /* done with axis locking */
839
840
841         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
842         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
843
844
845         /* touch all buttons between last mouse coord and this one */
846         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->but_type_start, drag_info->xy_last, xy);
847
848         if (do_draw) {
849                 ED_region_tag_redraw(ar);
850         }
851
852         copy_v2_v2_int(drag_info->xy_last, xy);
853 }
854
855 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
856 {
857         uiDragToggleHandle *drag_info = userdata;
858         MEM_freeN(drag_info);
859 }
860
861 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
862 {
863         uiDragToggleHandle *drag_info = userdata;
864         bool done = false;
865
866         switch (event->type) {
867                 case LEFTMOUSE:
868                 {
869                         if (event->val != KM_PRESS) {
870                                 done = true;
871                         }
872                         break;
873                 }
874                 case MOUSEMOVE:
875                 {
876                         ui_drag_toggle_set(C, drag_info, &event->x);
877                         break;
878                 }
879         }
880
881         if (done) {
882                 wmWindow *win = CTX_wm_window(C);
883                 WM_event_remove_ui_handler(&win->modalhandlers,
884                                            ui_handler_region_drag_toggle,
885                                            ui_handler_region_drag_toggle_remove,
886                                            drag_info, false);
887                 ui_handler_region_drag_toggle_remove(C, drag_info);
888
889                 WM_event_add_mousemove(C);
890                 return WM_UI_HANDLER_BREAK;
891         }
892         else {
893                 return WM_UI_HANDLER_CONTINUE;
894         }
895 }
896
897 #endif  /* USE_DRAG_TOGGLE */
898
899
900 static bool ui_but_mouse_inside_icon(uiBut *but, ARegion *ar, const wmEvent *event)
901 {
902         rcti rect;
903         int x = event->x, y = event->y;
904         
905         ui_window_to_block(ar, but->block, &x, &y);
906         
907         BLI_rcti_rctf_copy(&rect, &but->rect);
908         
909         if (but->imb) {
910                 /* use button size itself */
911         }
912         else if (but->flag & UI_ICON_LEFT) {
913                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
914         }
915         else {
916                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
917                 rect.xmin += delta / 2;
918                 rect.xmax -= delta / 2;
919         }
920         
921         return BLI_rcti_isect_pt(&rect, x, y);
922 }
923
924 static bool ui_but_start_drag(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
925 {
926         /* prevent other WM gestures to start while we try to drag */
927         WM_gestures_remove(C);
928
929         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
930
931                 button_activate_state(C, but, BUTTON_STATE_EXIT);
932                 data->cancel = true;
933 #ifdef USE_DRAG_TOGGLE
934                 if (ui_is_but_bool(but)) {
935                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
936
937                         drag_info->is_set = ui_is_but_push(but);
938                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
939                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
940                         drag_info->but_type_start = but->type;
941                         copy_v2_v2_int(drag_info->xy_last, &event->x);
942
943                         WM_event_add_ui_handler(C, &data->window->modalhandlers,
944                                                 ui_handler_region_drag_toggle,
945                                                 ui_handler_region_drag_toggle_remove,
946                                                 drag_info);
947                 }
948                 else
949 #endif
950                 {
951                         wmDrag *drag;
952
953                         drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_get_but_val(but));
954                         if (but->imb)
955                                 WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
956                 }
957                 return true;
958         }
959         
960         return false;
961 }
962
963 /* ********************** linklines *********************** */
964
965 static void ui_delete_active_linkline(uiBlock *block)
966 {
967         uiBut *but;
968         uiLink *link;
969         uiLinkLine *line, *nline;
970         int a, b;
971
972         for (but = block->buttons.first; but; but = but->next) {
973                 if (but->type == LINK && but->link) {
974                         for (line = but->link->lines.first; line; line = nline) {
975                                 nline = line->next;
976                                 
977                                 if (line->flag & UI_SELECT) {
978                                         BLI_remlink(&but->link->lines, line);
979                                         
980                                         link = line->from->link;
981                                         
982                                         /* are there more pointers allowed? */
983                                         if (link->ppoin) {
984                                                 
985                                                 if (*(link->totlink) == 1) {
986                                                         *(link->totlink) = 0;
987                                                         MEM_freeN(*(link->ppoin));
988                                                         *(link->ppoin) = NULL;
989                                                 }
990                                                 else {
991                                                         b = 0;
992                                                         for (a = 0; a < (*(link->totlink)); a++) {
993                                                                 
994                                                                 if ((*(link->ppoin))[a] != line->to->poin) {
995                                                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
996                                                                         b++;
997                                                                 }
998                                                         }
999                                                         (*(link->totlink))--;
1000                                                 }
1001                                         }
1002                                         else {
1003                                                 *(link->poin) = NULL;
1004                                         }
1005                                         
1006                                         MEM_freeN(line);
1007                                 }
1008                         }
1009                 }
1010         }
1011 }
1012
1013
1014 static uiLinkLine *ui_is_a_link(uiBut *from, uiBut *to)
1015 {
1016         uiLinkLine *line;
1017         uiLink *link;
1018         
1019         link = from->link;
1020         if (link) {
1021                 for (line = link->lines.first; line; line = line->next) {
1022                         if (line->from == from && line->to == to) {
1023                                 return line;
1024                         }
1025                 }
1026         }
1027         return NULL;
1028 }
1029
1030 /* XXX BAD BAD HACK, fixme later **************** */
1031 /* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */
1032 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
1033 {
1034         Object *ob = NULL;
1035         bSensor *sens_iter;
1036         bActuator *act_to, *act_iter;
1037         bController *cont;
1038         bController ***sens_from_links;
1039         uiBut *tmp_but;
1040
1041         uiLink *link = from->link;
1042
1043         PointerRNA props_ptr, object_ptr;
1044         
1045         if (link->ppoin)
1046                 sens_from_links = (bController ***)(link->ppoin);
1047         else return;
1048
1049         act_to = (bActuator *)(to->poin);
1050
1051         /* (1) get the object */
1052         CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects)
1053         {
1054                 for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) {
1055                         if (&(sens_iter->links) == sens_from_links) {
1056                                 ob = ob_iter;
1057                                 break;
1058                         }
1059                 }
1060                 if (ob) break;
1061         } CTX_DATA_END;
1062
1063         if (!ob) return;
1064
1065         /* (2) check if the sensor and the actuator are from the same object */
1066         for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) {
1067                 if (act_iter == act_to)
1068                         break;
1069         }
1070
1071         /* only works if the sensor and the actuator are from the same object */
1072         if (!act_iter) return;
1073         
1074         /* in case the linked controller is not the active one */
1075         RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
1076         
1077         WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
1078         RNA_string_set(&props_ptr, "object", ob->id.name + 2);
1079
1080         /* (3) add a new controller */
1081         if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
1082                 cont = (bController *)ob->controllers.last;
1083                 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... */
1084
1085                 /* (4) link the sensor->controller->actuator */
1086                 tmp_but = MEM_callocN(sizeof(uiBut), "uiBut");
1087                 uiSetButLink(tmp_but, (void **)&cont, (void ***)&(cont->links), &(cont->totlinks), from->link->tocode, (int)to->hardmin);
1088                 tmp_but->hardmin = from->link->tocode;
1089                 tmp_but->poin = (char *)cont;
1090
1091                 tmp_but->type = INLINK;
1092                 ui_add_link(C, from, tmp_but);
1093
1094                 tmp_but->type = LINK;
1095                 ui_add_link(C, tmp_but, to);
1096
1097                 /* (5) garbage collection */
1098                 MEM_freeN(tmp_but->link);
1099                 MEM_freeN(tmp_but);
1100         }
1101         WM_operator_properties_free(&props_ptr);
1102 }
1103
1104 static void ui_add_link(bContext *C, uiBut *from, uiBut *to)
1105 {
1106         /* in 'from' we have to add a link to 'to' */
1107         uiLink *link;
1108         uiLinkLine *line;
1109         void **oldppoin;
1110         int a;
1111         
1112         if ((line = ui_is_a_link(from, to))) {
1113                 line->flag |= UI_SELECT;
1114                 ui_delete_active_linkline(from->block);
1115                 return;
1116         }
1117
1118         if (from->type == INLINK && to->type == INLINK) {
1119                 return;
1120         }
1121         else if (from->type == LINK && to->type == INLINK) {
1122                 if (from->link->tocode != (int)to->hardmin) {
1123                         ui_add_smart_controller(C, from, to);
1124                         return;
1125                 }
1126         }
1127         else if (from->type == INLINK && to->type == LINK) {
1128                 if (to->link->tocode == (int)from->hardmin) {
1129                         return;
1130                 }
1131         }
1132         
1133         link = from->link;
1134         
1135         /* are there more pointers allowed? */
1136         if (link->ppoin) {
1137                 oldppoin = *(link->ppoin);
1138                 
1139                 (*(link->totlink))++;
1140                 *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link");
1141                 
1142                 for (a = 0; a < (*(link->totlink)) - 1; a++) {
1143                         (*(link->ppoin))[a] = oldppoin[a];
1144                 }
1145                 (*(link->ppoin))[a] = to->poin;
1146                 
1147                 if (oldppoin) MEM_freeN(oldppoin);
1148         }
1149         else {
1150                 *(link->poin) = to->poin;
1151         }
1152         
1153 }
1154
1155
1156 static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data)
1157 {
1158         ARegion *ar = CTX_wm_region(C);
1159         uiBut *bt;
1160         
1161         for (bt = but->block->buttons.first; bt; bt = bt->next) {
1162                 if (ui_mouse_inside_button(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) )
1163                         break;
1164         }
1165         if (bt && bt != but) {
1166                 if (!ELEM(bt->type, LINK, INLINK) || !ELEM(but->type, LINK, INLINK))
1167                         return;
1168                 
1169                 if (but->type == LINK) ui_add_link(C, but, bt);
1170                 else ui_add_link(C, bt, but);
1171
1172                 ui_apply_but_func(C, but);
1173                 data->retval = but->retval;
1174         }
1175         data->applied = true;
1176 }
1177
1178 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1179 {
1180         ui_apply_but_func(C, but);
1181         data->retval = but->retval;
1182         data->applied = true;
1183 }
1184
1185 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1186 {
1187         ui_apply_but_func(C, but);
1188         data->retval = but->retval;
1189         data->applied = true;
1190 }
1191
1192 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1193 {
1194         ui_apply_but_func(C, but);
1195         data->retval = but->retval;
1196         data->applied = true;
1197 }
1198
1199 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1200 {
1201         ui_apply_but_func(C, but);
1202         data->retval = but->retval;
1203         data->applied = true;
1204 }
1205
1206
1207 static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1208 {
1209         char *editstr;
1210         double *editval;
1211         float *editvec;
1212         ColorBand *editcoba;
1213         CurveMapping *editcumap;
1214
1215         data->retval = 0;
1216
1217         /* if we cancel and have not applied yet, there is nothing to do,
1218          * otherwise we have to restore the original value again */
1219         if (data->cancel) {
1220                 if (!data->applied)
1221                         return;
1222
1223                 if (data->str) MEM_freeN(data->str);
1224                 data->str = data->origstr;
1225                 data->origstr = NULL;
1226                 data->value = data->origvalue;
1227                 data->origvalue = 0.0;
1228                 copy_v3_v3(data->vec, data->origvec);
1229                 data->origvec[0] = data->origvec[1] = data->origvec[2] = 0.0f;
1230         }
1231         else {
1232                 /* we avoid applying interactive edits a second time
1233                  * at the end with the appliedinteractive flag */
1234                 if (interactive) {
1235                         data->applied_interactive = true;
1236                 }
1237                 else if (data->applied_interactive) {
1238                         return;
1239                 }
1240         }
1241
1242         /* ensures we are writing actual values */
1243         editstr = but->editstr;
1244         editval = but->editval;
1245         editvec = but->editvec;
1246         editcoba = but->editcoba;
1247         editcumap = but->editcumap;
1248         but->editstr = NULL;
1249         but->editval = NULL;
1250         but->editvec = NULL;
1251         but->editcoba = NULL;
1252         but->editcumap = NULL;
1253
1254         /* handle different types */
1255         switch (but->type) {
1256                 case BUT:
1257                         ui_apply_but_BUT(C, but, data);
1258                         break;
1259                 case TEX:
1260                 case SEARCH_MENU_UNLINK:
1261                 case SEARCH_MENU:
1262                         ui_apply_but_TEX(C, but, data);
1263                         break;
1264                 case TOGBUT: 
1265                 case TOG: 
1266                 case TOGR: 
1267                 case ICONTOG:
1268                 case ICONTOGN:
1269                 case TOGN:
1270                 case BUT_TOGDUAL:
1271                 case OPTION:
1272                 case OPTIONN:
1273                         ui_apply_but_TOG(C, but, data);
1274                         break;
1275                 case ROW:
1276                 case LISTROW:
1277                         ui_apply_but_ROW(C, block, but, data);
1278                         break;
1279                 case SCROLL:
1280                 case NUM:
1281                 case NUMABS:
1282                 case SLI:
1283                 case NUMSLI:
1284                         ui_apply_but_NUM(C, but, data);
1285                         break;
1286                 case TOG3:
1287                         ui_apply_but_TOG3(C, but, data);
1288                         break;
1289                 case MENU:
1290                 case ICONROW:
1291                 case ICONTEXTROW:
1292                 case BLOCK:
1293                 case PULLDOWN:
1294                         ui_apply_but_BLOCK(C, but, data);
1295                         break;
1296                 case COLOR:
1297                         if (data->cancel)
1298                                 ui_apply_but_VEC(C, but, data);
1299                         else
1300                                 ui_apply_but_BLOCK(C, but, data);
1301                         break;
1302                 case BUTM:
1303                         ui_apply_but_BUTM(C, but, data);
1304                         break;
1305                 case BUT_NORMAL:
1306                 case HSVCUBE:
1307                 case HSVCIRCLE:
1308                         ui_apply_but_VEC(C, but, data);
1309                         break;
1310                 case BUT_COLORBAND:
1311                         ui_apply_but_COLORBAND(C, but, data);
1312                         break;
1313                 case BUT_CURVE:
1314                         ui_apply_but_CURVE(C, but, data);
1315                         break;
1316                 case IDPOIN:
1317                         ui_apply_but_IDPOIN(C, but, data);
1318                         break;
1319 #ifdef WITH_INTERNATIONAL
1320                 case CHARTAB:
1321                         ui_apply_but_CHARTAB(C, but, data);
1322                         break;
1323 #endif
1324                 case KEYEVT:
1325                 case HOTKEYEVT:
1326                         ui_apply_but_BUT(C, but, data);
1327                         break;
1328                 case LINK:
1329                 case INLINK:
1330                         ui_apply_but_LINK(C, but, data);
1331                         break;
1332                 case BUT_IMAGE:
1333                         ui_apply_but_IMAGE(C, but, data);
1334                         break;
1335                 case HISTOGRAM:
1336                         ui_apply_but_HISTOGRAM(C, but, data);
1337                         break;
1338                 case WAVEFORM:
1339                         ui_apply_but_WAVEFORM(C, but, data);
1340                         break;
1341                 case TRACKPREVIEW:
1342                         ui_apply_but_TRACKPREVIEW(C, but, data);
1343                         break;
1344                 default:
1345                         break;
1346         }
1347
1348         but->editstr = editstr;
1349         but->editval = editval;
1350         but->editvec = editvec;
1351         but->editcoba = editcoba;
1352         but->editcumap = editcumap;
1353 }
1354
1355 /* ******************* drop event ********************  */
1356
1357 /* only call if event type is EVT_DROP */
1358 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
1359 {
1360         wmDrag *wmd;
1361         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
1362         
1363         for (wmd = drags->first; wmd; wmd = wmd->next) {
1364                 if (wmd->type == WM_DRAG_ID) {
1365                         /* align these types with UI_but_active_drop_name */
1366                         if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1367                                 ID *id = (ID *)wmd->poin;
1368                                 
1369                                 if (but->poin == NULL && but->rnapoin.data == NULL) {}
1370                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1371                                 BLI_strncpy(data->str, id->name + 2, data->maxlen);
1372                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1373                         }
1374                 }
1375         }
1376         
1377 }
1378
1379 /* ******************* copy and paste ********************  */
1380
1381 /* c = copy, v = paste */
1382 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, char mode)
1383 {
1384         static ColorBand but_copypaste_coba = {0};
1385         char buf[UI_MAX_DRAW_STR + 1] = {0};
1386
1387         if (mode == 'v' && but->lock  == TRUE) {
1388                 return;
1389         }
1390
1391         if (mode == 'v') {
1392                 /* extract first line from clipboard in case of multi-line copies */
1393                 char *p, *pbuf = WM_clipboard_text_get(0);
1394                 p = pbuf;
1395                 if (p) {
1396                         int i = 0;
1397                         while (*p && *p != '\r' && *p != '\n' && i < UI_MAX_DRAW_STR) {
1398                                 buf[i++] = *p;
1399                                 p++;
1400                         }
1401                         buf[i] = 0;
1402                         MEM_freeN(pbuf);
1403                 }
1404         }
1405         
1406         /* numeric value */
1407         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
1408                 
1409                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1410                         /* pass */
1411                 }
1412                 else if (mode == 'c') {
1413                         /* Get many decimal places, then strip trailing zeros.
1414                          * note: too high values start to give strange results (6 or so is ok) */
1415                         ui_get_but_string_ex(but, buf, sizeof(buf), 6);
1416                         BLI_str_rstrip_float_zero(buf, '\0');
1417
1418                         WM_clipboard_text_set(buf, 0);
1419                 }
1420                 else {
1421                         double val;
1422
1423                         if (ui_set_but_string_eval_num(C, but, buf, &val)) {
1424                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1425                                 data->value = val;
1426                                 ui_set_but_string(C, but, buf);
1427                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1428                         }
1429                 }
1430         }
1431
1432         /* RGB triple */
1433         else if (but->type == COLOR) {
1434                 float rgba[4];
1435                 
1436                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1437                         /* pass */
1438                 }
1439                 else if (mode == 'c') {
1440                         if (RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1441                                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
1442                         else
1443                                 rgba[3] = 1.0f;
1444                         
1445                         ui_get_but_vectorf(but, rgba);
1446                         /* convert to linear color to do compatible copy between gamma and non-gamma */
1447                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1448                                 srgb_to_linearrgb_v3_v3(rgba, rgba);
1449
1450                         BLI_snprintf(buf, sizeof(buf), "[%f, %f, %f, %f]", rgba[0], rgba[1], rgba[2], rgba[3]);
1451                         WM_clipboard_text_set(buf, 0);
1452                         
1453                 }
1454                 else {
1455                         if (sscanf(buf, "[%f, %f, %f, %f]", &rgba[0], &rgba[1], &rgba[2], &rgba[3]) == 4) {
1456                                 /* assume linear colors in buffer */
1457                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1458                                         linearrgb_to_srgb_v3_v3(rgba, rgba);
1459
1460                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1461                                 ui_set_but_vectorf(but, rgba);
1462                                 if (RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1463                                         RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, rgba[3]);
1464
1465                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1466                         }
1467                 }
1468         }
1469
1470         /* text/string and ID data */
1471         else if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1472                 uiHandleButtonData *active_data = but->active;
1473
1474                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1475                         /* pass */
1476                 }
1477                 else if (mode == 'c') {
1478                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1479                         BLI_strncpy(buf, active_data->str, UI_MAX_DRAW_STR);
1480                         WM_clipboard_text_set(active_data->str, 0);
1481                         active_data->cancel = true;
1482                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1483                 }
1484                 else {
1485                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1486
1487                         if (ui_is_but_utf8(but)) BLI_strncpy_utf8(active_data->str, buf, active_data->maxlen);
1488                         else BLI_strncpy(active_data->str, buf, active_data->maxlen);
1489
1490                         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1491                                 /* else uiSearchboxData.active member is not updated [#26856] */
1492                                 ui_searchbox_update(C, data->searchbox, but, true);
1493                         }
1494                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1495                 }
1496         }
1497         /* colorband (not supported by system clipboard) */
1498         else if (but->type == BUT_COLORBAND) {
1499                 if (mode == 'c') {
1500                         if (but->poin == NULL)
1501                                 return;
1502
1503                         memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
1504                 }
1505                 else {
1506                         if (but_copypaste_coba.tot == 0)
1507                                 return;
1508
1509                         if (!but->poin)
1510                                 but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
1511
1512                         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1513                         memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
1514                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1515                 }
1516         }
1517         /* operator button (any type) */
1518         else if (but->optype) {
1519                 if (mode == 'c') {
1520                         PointerRNA *opptr;
1521                         char *str;
1522                         opptr = uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
1523
1524                         str = WM_operator_pystring(C, but->optype, opptr, 0);
1525
1526                         WM_clipboard_text_set(str, 0);
1527
1528                         MEM_freeN(str);
1529                 }
1530         }
1531 }
1532
1533 /* ************************ password text ******************************
1534  *
1535  * Functions to convert password strings that should not be displayed
1536  * to asterisk representation (e.g. mysecretpasswd -> *************)
1537  *
1538  * It converts every UTF-8 character to an asterisk, and also remaps
1539  * the cursor position and selection start/end.
1540  *
1541  * Note: remaping is used, because password could contain UTF-8 characters.
1542  *
1543  */
1544
1545 static int ui_text_position_from_hidden(uiBut *but, int pos)
1546 {
1547         const char *strpos;
1548         int i;
1549
1550         for (i = 0, strpos = but->drawstr; i < pos; i++)
1551                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
1552         
1553         return (strpos - but->drawstr);
1554 }
1555
1556 static int ui_text_position_to_hidden(uiBut *but, int pos)
1557 {
1558         return BLI_strnlen_utf8(but->drawstr, pos);
1559 }
1560
1561 void ui_button_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut *but, int restore)
1562 {
1563         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
1564                 return;
1565
1566         if (restore) {
1567                 /* restore original string */
1568                 BLI_strncpy(but->drawstr, password_str, UI_MAX_DRAW_STR);
1569
1570                 /* remap cursor positions */
1571                 if (but->pos >= 0) {
1572                         but->pos = ui_text_position_from_hidden(but, but->pos);
1573                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
1574                         but->selend = ui_text_position_from_hidden(but, but->selend);
1575                 }
1576         }
1577         else {
1578                 /* convert text to hidden test using asterisks (e.g. pass -> ****) */
1579                 int i, len = BLI_strlen_utf8(but->drawstr);
1580
1581                 /* remap cursor positions */
1582                 if (but->pos >= 0) {
1583                         but->pos = ui_text_position_to_hidden(but, but->pos);
1584                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
1585                         but->selend = ui_text_position_to_hidden(but, but->selend);
1586                 }
1587
1588                 /* save original string */
1589                 BLI_strncpy(password_str, but->drawstr, UI_MAX_DRAW_STR);
1590
1591                 for (i = 0; i < len; i++)
1592                         but->drawstr[i] = '*';
1593                 but->drawstr[i] = '\0';
1594         }
1595 }
1596
1597
1598 /* ************* in-button text selection/editing ************* */
1599
1600
1601 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
1602 {
1603         char *str = data->str;
1604         const int len = strlen(str);
1605         bool change = false;
1606         if (but->selsta != but->selend && len) {
1607                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
1608                 change = true;
1609         }
1610         
1611         but->pos = but->selend = but->selsta;
1612         return change;
1613 }
1614
1615 /* note, but->block->aspect is used here, when drawing button style is getting scaled too */
1616 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
1617 {
1618         uiStyle *style = UI_GetStyle();  // XXX pass on as arg
1619         uiFontStyle *fstyle = &style->widget;
1620         float startx = but->rect.xmin;
1621         char *origstr, password_str[UI_MAX_DRAW_STR];
1622
1623         uiStyleFontSet(fstyle);
1624
1625         if (fstyle->kerning == 1) /* for BLF_width */
1626                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1627         
1628         ui_button_text_password_hide(password_str, but, FALSE);
1629
1630         origstr = MEM_mallocN(sizeof(char) * data->maxlen, "ui_textedit origstr");
1631         
1632         BLI_strncpy(origstr, but->drawstr, data->maxlen);
1633         
1634         /* XXX solve generic, see: #widget_draw_text_icon */
1635         if (but->type == NUM || but->type == NUMSLI) {
1636                 startx += (int)(0.5f * (BLI_rctf_size_y(&but->rect)));
1637         }
1638         else if (ELEM3(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1639                 if (but->flag & UI_HAS_ICON) {
1640                         startx += UI_DPI_ICON_SIZE;
1641                 }
1642                 /* but this extra .05 makes clicks inbetween characters feel nicer */
1643                 startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit);
1644         }
1645         
1646         /* mouse dragged outside the widget to the left */
1647         if (x < startx) {
1648                 int i = but->ofs;
1649
1650                 origstr[but->ofs] = '\0';
1651                 
1652                 while (i > 0) {
1653                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &i)) {
1654                                 /* 0.25 == scale factor for less sensitivity */
1655                                 if (BLF_width(fstyle->uifont_id, origstr + i) > (startx - x) * 0.25f) {
1656                                         break;
1657                                 }
1658                         }
1659                         else {
1660                                 break; /* unlikely but possible */
1661                         }
1662                 }
1663                 but->ofs = i;
1664                 but->pos = but->ofs;
1665         }
1666         /* mouse inside the widget, mouse coords mapped in widget space */
1667         else {  /* (x >= startx) */
1668                 int pos_i;
1669
1670                 /* keep track of previous distance from the cursor to the char */
1671                 float cdist, cdist_prev = 0.0f;
1672                 short pos_prev;
1673                 
1674                 but->pos = pos_prev = strlen(origstr) - but->ofs;
1675
1676                 while (true) {
1677                         cdist = startx + BLF_width(fstyle->uifont_id, origstr + but->ofs);
1678
1679                         /* check if position is found */
1680                         if (cdist < x) {
1681                                 /* check is previous location was in fact closer */
1682                                 if (((float)x - cdist) > (cdist_prev - (float)x)) {
1683                                         but->pos = pos_prev;
1684                                 }
1685                                 break;
1686                         }
1687                         cdist_prev = cdist;
1688                         pos_prev   = but->pos;
1689                         /* done with tricky distance checks */
1690
1691                         pos_i = but->pos;
1692                         if (but->pos <= 0) break;
1693                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &pos_i)) {
1694                                 but->pos = pos_i;
1695                                 origstr[but->pos + but->ofs] = 0;
1696                         }
1697                         else {
1698                                 break; /* unlikely but possible */
1699                         }
1700                 }
1701                 but->pos += but->ofs;
1702                 if (but->pos < 0) but->pos = 0;
1703         }
1704         
1705         if (fstyle->kerning == 1)
1706                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1707         
1708         ui_button_text_password_hide(password_str, but, TRUE);
1709
1710         MEM_freeN(origstr);
1711 }
1712
1713 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
1714 {
1715         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
1716         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
1717
1718         ui_textedit_set_cursor_pos(but, data, x);
1719
1720         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
1721         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
1722
1723         ui_check_but(but);
1724 }
1725
1726 /* this is used for both utf8 and ascii, its meant to be used for single keys,
1727  * notice the buffer is either copied or not, so its not suitable for pasting in
1728  * - campbell */
1729 static bool ui_textedit_type_buf(uiBut *but, uiHandleButtonData *data,
1730                                  const char *utf8_buf, int utf8_buf_len)
1731 {
1732         char *str;
1733         int len;
1734         bool changed = false;
1735
1736         str = data->str;
1737         len = strlen(str);
1738
1739         if (len - (but->selend - but->selsta) + 1 <= data->maxlen) {
1740                 int step = utf8_buf_len;
1741
1742                 /* type over the current selection */
1743                 if ((but->selend - but->selsta) > 0) {
1744                         changed = ui_textedit_delete_selection(but, data);
1745                         len = strlen(str);
1746                 }
1747
1748                 if (len + step < data->maxlen) {
1749                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
1750                         memcpy(&str[but->pos], utf8_buf, step * sizeof(char));
1751                         but->pos += step;
1752                         changed = true;
1753                 }
1754         }
1755
1756         return changed;
1757 }
1758
1759 static bool ui_textedit_type_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
1760 {
1761         char buf[2] = {ascii, '\0'};
1762
1763         if (ui_is_but_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
1764                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
1765                        __func__, (int)(unsigned char)ascii);
1766
1767                 return false;
1768         }
1769
1770         /* in some cases we want to allow invalid utf8 chars */
1771         return ui_textedit_type_buf(but, data, buf, 1);
1772 }
1773
1774 static void ui_textedit_move(uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
1775                              int select, strCursorJumpType jump)
1776 {
1777         const char *str = data->str;
1778         const int len = strlen(str);
1779         const int pos_prev = but->pos;
1780         const int has_sel = (but->selend - but->selsta) > 0;
1781
1782         ui_check_but(but);
1783
1784         /* special case, quit selection and set cursor */
1785         if (has_sel && !select) {
1786                 if (jump == STRCUR_JUMP_ALL) {
1787                         but->selsta = but->selend = but->pos = direction ? len : 0;
1788                 }
1789                 else {
1790                         if (direction) {
1791                                 but->selsta = but->pos = but->selend;
1792                         }
1793                         else {
1794                                 but->pos = but->selend = but->selsta;
1795                         }
1796                 }
1797                 data->selextend = 0;
1798         }
1799         else {
1800                 int pos_i = but->pos;
1801                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
1802                 but->pos = pos_i;
1803
1804                 if (select) {
1805                         /* existing selection */
1806                         if (has_sel) {
1807
1808                                 if (data->selextend == 0) {
1809                                         data->selextend = EXTEND_RIGHT;
1810                                 }
1811
1812                                 if (direction) {
1813                                         if (data->selextend == EXTEND_RIGHT) {
1814                                                 but->selend = but->pos;
1815                                         }
1816                                         else {
1817                                                 but->selsta = but->pos;
1818                                         }
1819                                 }
1820                                 else {
1821                                         if (data->selextend == EXTEND_LEFT) {
1822                                                 but->selsta = but->pos;
1823                                         }
1824                                         else {
1825                                                 but->selend = but->pos;
1826                                         }
1827                                 }
1828
1829                                 if (but->selend < but->selsta) {
1830                                         SWAP(short, but->selsta, but->selend);
1831                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
1832                                 }
1833
1834                         } /* new selection */
1835                         else {
1836                                 if (direction) {
1837                                         data->selextend = EXTEND_RIGHT;
1838                                         but->selend = but->pos;
1839                                         but->selsta = pos_prev;
1840                                 }
1841                                 else {
1842                                         data->selextend = EXTEND_LEFT;
1843                                         but->selend = pos_prev;
1844                                         but->selsta = but->pos;
1845                                 }
1846                         }
1847                 }
1848         }
1849 }
1850
1851 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
1852 {
1853         char *str = data->str;
1854         const int len = strlen(str);
1855
1856         bool changed = false;
1857
1858         if (jump == STRCUR_JUMP_ALL) {
1859                 if (len) changed = true;
1860                 str[0] = '\0';
1861                 but->pos = 0;
1862         }
1863         else if (direction) { /* delete */
1864                 if ((but->selend - but->selsta) > 0) {
1865                         changed = ui_textedit_delete_selection(but, data);
1866                 }
1867                 else if (but->pos >= 0 && but->pos < len) {
1868                         int pos = but->pos;
1869                         int step;
1870                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
1871                         step = pos - but->pos;
1872                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - but->pos);
1873                         changed = true;
1874                 }
1875         }
1876         else { /* backspace */
1877                 if (len != 0) {
1878                         if ((but->selend - but->selsta) > 0) {
1879                                 changed = ui_textedit_delete_selection(but, data);
1880                         }
1881                         else if (but->pos > 0) {
1882                                 int pos = but->pos;
1883                                 int step;
1884
1885                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
1886                                 step = but->pos - pos;
1887                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
1888                                 but->pos -= step;
1889                                 changed = true;
1890                         }
1891                 }
1892         }
1893
1894         return changed;
1895 }
1896
1897 static bool ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
1898 {
1899         char *str;
1900         /* TODO, should return false if it cant autocomp. */
1901         bool changed = true;
1902
1903         str = data->str;
1904
1905         if (data->searchbox)
1906                 ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
1907         else
1908                 but->autocomplete_func(C, str, but->autofunc_arg);
1909
1910         but->pos = strlen(str);
1911         but->selsta = but->selend = but->pos;
1912
1913         return changed;
1914 }
1915
1916 /* mode for ui_textedit_copypaste() */
1917 enum {
1918         UI_TEXTEDIT_PASTE = 1,
1919         UI_TEXTEDIT_COPY,
1920         UI_TEXTEDIT_CUT
1921 };
1922
1923 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
1924 {
1925         char buf[UI_MAX_DRAW_STR] = {0};
1926         char *str, *p, *pbuf;
1927         int x;
1928         bool changed = false;
1929         int str_len, buf_len;
1930
1931         str = data->str;
1932         str_len = strlen(str);
1933         
1934         /* paste */
1935         if (mode == UI_TEXTEDIT_PASTE) {
1936                 /* TODO, ensure UTF8 ui_is_but_utf8() - campbell */
1937                 /* extract the first line from the clipboard */
1938                 p = pbuf = WM_clipboard_text_get(0);
1939
1940                 if (p && p[0]) {
1941                         unsigned int y;
1942                         buf_len = 0;
1943                         while (*p && *p != '\r' && *p != '\n' && buf_len < UI_MAX_DRAW_STR - 1) {
1944                                 buf[buf_len++] = *p;
1945                                 p++;
1946                         }
1947                         buf[buf_len] = 0;
1948
1949                         /* paste over the current selection */
1950                         if ((but->selend - but->selsta) > 0) {
1951                                 ui_textedit_delete_selection(but, data);
1952                                 str_len = strlen(str);
1953                         }
1954                         
1955                         for (y = 0; y < buf_len; y++) {
1956                                 /* add contents of buffer */
1957                                 if (str_len + 1 < data->maxlen) {
1958                                         for (x = data->maxlen; x > but->pos; x--)
1959                                                 str[x] = str[x - 1];
1960                                         str[but->pos] = buf[y];
1961                                         but->pos++; 
1962                                         str_len++;
1963                                         str[str_len] = '\0';
1964                                 }
1965                         }
1966
1967                         changed = true;
1968                 }
1969
1970                 if (pbuf) {
1971                         MEM_freeN(pbuf);
1972                 }
1973         }
1974         /* cut & copy */
1975         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
1976                 /* copy the contents to the copypaste buffer */
1977                 for (x = but->selsta; x <= but->selend; x++) {
1978                         if (x == but->selend)
1979                                 buf[x] = '\0';
1980                         else
1981                                 buf[(x - but->selsta)] = str[x];
1982                 }
1983
1984                 WM_clipboard_text_set(buf, 0);
1985                 
1986                 /* for cut only, delete the selection afterwards */
1987                 if (mode == UI_TEXTEDIT_CUT) {
1988                         if ((but->selend - but->selsta) > 0) {
1989                                 changed = ui_textedit_delete_selection(but, data);
1990                         }
1991                 }
1992         }
1993
1994         return changed;
1995 }
1996
1997 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
1998 {
1999         int len;
2000
2001         if (data->str) {
2002                 MEM_freeN(data->str);
2003                 data->str = NULL;
2004         }
2005
2006         /* retrieve string */
2007         data->maxlen = ui_get_but_string_max_length(but);
2008         data->str = MEM_callocN(sizeof(char) * data->maxlen + 1, "textedit str");
2009         ui_get_but_string(but, data->str, data->maxlen);
2010
2011         if (ui_is_but_float(but) && !ui_is_but_unit(but)) {
2012                 BLI_str_rstrip_float_zero(data->str, '\0');
2013         }
2014
2015         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
2016                 ui_convert_to_unit_alt_name(but, data->str, data->maxlen);
2017         }
2018
2019         /* won't change from now on */
2020         len = strlen(data->str);
2021
2022         data->origstr = BLI_strdupn(data->str, len);
2023         data->selextend = 0;
2024         data->selstartx = 0;
2025
2026         /* set cursor pos to the end of the text */
2027         but->editstr = data->str;
2028         but->pos = len;
2029         but->selsta = 0;
2030         but->selend = len;
2031
2032         /* optional searchbox */
2033         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2034                 data->searchbox = ui_searchbox_create(C, data->region, but);
2035                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
2036         }
2037
2038         /* reset alert flag (avoid confusion, will refresh on exit) */
2039         but->flag &= ~UI_BUT_REDALERT;
2040
2041         ui_check_but(but);
2042         
2043         WM_cursor_modal(CTX_wm_window(C), BC_TEXTEDITCURSOR);
2044 }
2045
2046 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2047 {
2048         if (but) {
2049                 if (ui_is_but_utf8(but)) {
2050                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
2051                         /* not a file?, strip non utf-8 chars */
2052                         if (strip) {
2053                                 /* wont happen often so isn't that annoying to keep it here for a while */
2054                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
2055                         }
2056                 }
2057                 
2058                 if (data->searchbox) {
2059                         if (data->cancel == false) {
2060                                 if ((ui_searchbox_apply(but, data->searchbox) == false) ||
2061                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
2062                                 {
2063                                         data->cancel = true;
2064                                 }
2065                         }
2066
2067                         ui_searchbox_free(C, data->searchbox);
2068                         data->searchbox = NULL;
2069                 }
2070                 
2071                 but->editstr = NULL;
2072                 but->pos = -1;
2073         }
2074         
2075         WM_cursor_restore(CTX_wm_window(C));
2076 }
2077
2078 static void ui_textedit_next_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2079 {
2080         uiBut *but;
2081
2082         /* label and roundbox can overlap real buttons (backdrops...) */
2083         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
2084                 return;
2085
2086         for (but = actbut->next; but; but = but->next) {
2087                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2088                         if (!(but->flag & UI_BUT_DISABLED)) {
2089                                 data->postbut = but;
2090                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2091                                 return;
2092                         }
2093                 }
2094         }
2095         for (but = block->buttons.first; but != actbut; but = but->next) {
2096                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2097                         if (!(but->flag & UI_BUT_DISABLED)) {
2098                                 data->postbut = but;
2099                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2100                                 return;
2101                         }
2102                 }
2103         }
2104 }
2105
2106 static void ui_textedit_prev_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2107 {
2108         uiBut *but;
2109
2110         /* label and roundbox can overlap real buttons (backdrops...) */
2111         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
2112                 return;
2113
2114         for (but = actbut->prev; but; but = but->prev) {
2115                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2116                         if (!(but->flag & UI_BUT_DISABLED)) {
2117                                 data->postbut = but;
2118                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2119                                 return;
2120                         }
2121                 }
2122         }
2123         for (but = block->buttons.last; but != actbut; but = but->prev) {
2124                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2125                         if (!(but->flag & UI_BUT_DISABLED)) {
2126                                 data->postbut = but;
2127                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2128                                 return;
2129                         }
2130                 }
2131         }
2132 }
2133
2134
2135 static void ui_do_but_textedit(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2136 {
2137         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2138         bool changed = false, inbox = false, update = false;
2139
2140         switch (event->type) {
2141                 case MOUSEMOVE:
2142                 case MOUSEPAN:
2143                         if (data->searchbox) {
2144 #ifdef USE_KEYNAV_LIMIT
2145                                 if ((event->type == MOUSEMOVE) && ui_mouse_motion_keynav_test(&data->searchbox_keynav_state, event)) {
2146                                         /* pass */
2147                                 }
2148                                 else {
2149                                         ui_searchbox_event(C, data->searchbox, but, event);
2150                                 }
2151 #else
2152                                 ui_searchbox_event(C, data->searchbox, but, event);
2153 #endif
2154                         }
2155                         
2156                         break;
2157                 case RIGHTMOUSE:
2158                 case ESCKEY:
2159                         data->cancel = true;
2160                         data->escapecancel = true;
2161                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2162                         retval = WM_UI_HANDLER_BREAK;
2163                         break;
2164                 case LEFTMOUSE:
2165                 {
2166                         /* exit on LMB only on RELEASE for searchbox, to mimic other popups, and allow multiple menu levels */
2167                         if (data->searchbox)
2168                                 inbox = ui_searchbox_inside(data->searchbox, event->x, event->y);
2169
2170                         if (event->val == KM_PRESS) {
2171                                 mx = event->x;
2172                                 my = event->y;
2173                                 ui_window_to_block(data->region, block, &mx, &my);
2174
2175                                 if (ui_but_contains_pt(but, mx, my)) {
2176                                         ui_textedit_set_cursor_pos(but, data, mx);
2177                                         but->selsta = but->selend = but->pos;
2178                                         data->selstartx = mx;
2179
2180                                         button_activate_state(C, but, BUTTON_STATE_TEXT_SELECTING);
2181                                         retval = WM_UI_HANDLER_BREAK;
2182                                 }
2183                                 else if (inbox == false) {
2184                                         /* if searchbox, click outside will cancel */
2185                                         if (data->searchbox)
2186                                                 data->cancel = data->escapecancel = true;
2187                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2188                                         retval = WM_UI_HANDLER_BREAK;
2189                                 }
2190                         }
2191                         else if (inbox) {
2192                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2193                                 retval = WM_UI_HANDLER_BREAK;
2194                         }
2195                         break;
2196                 }
2197         }
2198
2199         if (event->val == KM_PRESS) {
2200                 switch (event->type) {
2201                         case VKEY:
2202                         case XKEY:
2203                         case CKEY:
2204                                 if (event->ctrl || event->oskey) {
2205                                         if (event->type == VKEY)
2206                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_PASTE);
2207                                         else if (event->type == CKEY)
2208                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_COPY);
2209                                         else if (event->type == XKEY)
2210                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_CUT);
2211
2212                                         retval = WM_UI_HANDLER_BREAK;
2213                                 }
2214                                 break;
2215                         case RIGHTARROWKEY:
2216                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2217                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2218                                 retval = WM_UI_HANDLER_BREAK;
2219                                 break;
2220                         case LEFTARROWKEY:
2221                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2222                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2223                                 retval = WM_UI_HANDLER_BREAK;
2224                                 break;
2225                         case WHEELDOWNMOUSE:
2226                         case DOWNARROWKEY:
2227                                 if (data->searchbox) {
2228 #ifdef USE_KEYNAV_LIMIT
2229                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2230 #endif
2231                                         ui_searchbox_event(C, data->searchbox, but, event);
2232                                         break;
2233                                 }
2234                         /* pass on purposedly */
2235                         case ENDKEY:
2236                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2237                                                  event->shift, STRCUR_JUMP_ALL);
2238                                 retval = WM_UI_HANDLER_BREAK;
2239                                 break;
2240                         case WHEELUPMOUSE:
2241                         case UPARROWKEY:
2242                                 if (data->searchbox) {
2243 #ifdef USE_KEYNAV_LIMIT
2244                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2245 #endif
2246                                         ui_searchbox_event(C, data->searchbox, but, event);
2247                                         break;
2248                                 }
2249                         /* pass on purposedly */
2250                         case HOMEKEY:
2251                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2252                                                  event->shift, STRCUR_JUMP_ALL);
2253                                 retval = WM_UI_HANDLER_BREAK;
2254                                 break;
2255                         case PADENTER:
2256                         case RETKEY:
2257                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2258                                 retval = WM_UI_HANDLER_BREAK;
2259                                 break;
2260                         case DELKEY:
2261                                 changed = ui_textedit_delete(but, data, 1,
2262                                                              event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2263                                 retval = WM_UI_HANDLER_BREAK;
2264                                 break;
2265
2266                         case BACKSPACEKEY:
2267                                 changed = ui_textedit_delete(but, data, 0,
2268                                                              event->shift ? STRCUR_JUMP_ALL : (event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE));
2269                                 retval = WM_UI_HANDLER_BREAK;
2270                                 break;
2271                                 
2272                         case AKEY:
2273                                 /* Ctrl + A: Select all */
2274                                 if (event->ctrl && !(event->alt || event->shift || event->oskey)) {
2275                                         ui_textedit_move(but, data, STRCUR_DIR_PREV,
2276                                                          false, STRCUR_JUMP_ALL);
2277                                         ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2278                                                          true, STRCUR_JUMP_ALL);
2279                                         retval = WM_UI_HANDLER_BREAK;
2280                                 }
2281                                 break;
2282
2283                         case TABKEY:
2284                                 /* there is a key conflict here, we can't tab with autocomplete */
2285                                 if (but->autocomplete_func || data->searchbox) {
2286                                         changed = ui_textedit_autocomplete(C, but, data);
2287                                         update = true;  /* do live update for tab key */
2288                                 }
2289                                 /* the hotkey here is not well defined, was G.qual so we check all */
2290                                 else if (event->shift || event->ctrl || event->alt || event->oskey) {
2291                                         ui_textedit_prev_but(block, but, data);
2292                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2293                                 }
2294                                 else {
2295                                         ui_textedit_next_but(block, but, data);
2296                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2297                                 }
2298                                 retval = WM_UI_HANDLER_BREAK;
2299                                 break;
2300                 }
2301
2302                 if ((event->ascii || event->utf8_buf[0]) && (retval == WM_UI_HANDLER_CONTINUE)) {
2303                         char ascii = event->ascii;
2304                         const char *utf8_buf = event->utf8_buf;
2305
2306                         /* exception that's useful for number buttons, some keyboard
2307                          * numpads have a comma instead of a period */
2308                         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) { /* could use data->min*/
2309                                 if (event->type == PADPERIOD && ascii == ',') {
2310                                         ascii = '.';
2311                                         utf8_buf = NULL; /* force ascii fallback */
2312                                 }
2313                         }
2314
2315                         if (utf8_buf && utf8_buf[0]) {
2316                                 int utf8_buf_len = BLI_str_utf8_size(utf8_buf);
2317                                 /* keep this printf until utf8 is well tested */
2318                                 if (utf8_buf_len != 1) {
2319                                         printf("%s: utf8 char '%.*s'\n", __func__, utf8_buf_len, utf8_buf);
2320                                 }
2321
2322                                 // strcpy(utf8_buf, "12345");
2323                                 changed = ui_textedit_type_buf(but, data, event->utf8_buf, utf8_buf_len);
2324                         }
2325                         else {
2326                                 changed = ui_textedit_type_ascii(but, data, ascii);
2327                         }
2328
2329                         retval = WM_UI_HANDLER_BREAK;
2330                         
2331                 }
2332                 /* textbutton with magnifier icon: do live update for search button */
2333                 if (but->icon == ICON_VIEWZOOM)
2334                         update = true;
2335         }
2336
2337         if (changed) {
2338                 /* only update when typing for TAB key */
2339                 if (update && data->interactive) {
2340                         ui_apply_button(C, block, but, data, true);
2341                 }
2342                 else {
2343                         ui_check_but(but);
2344                 }
2345                 but->changed = true;
2346                 
2347                 if (data->searchbox)
2348                         ui_searchbox_update(C, data->searchbox, but, true);  /* true = reset */
2349         }
2350
2351         if (changed || (retval == WM_UI_HANDLER_BREAK))
2352                 ED_region_tag_redraw(data->region);
2353 }
2354
2355 static void ui_do_but_textedit_select(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2356 {
2357         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2358
2359         switch (event->type) {
2360                 case MOUSEMOVE:
2361                 {
2362                         mx = event->x;
2363                         my = event->y;
2364                         ui_window_to_block(data->region, block, &mx, &my);
2365
2366                         ui_textedit_set_cursor_select(but, data, mx);
2367                         retval = WM_UI_HANDLER_BREAK;
2368                         break;
2369                 }
2370                 case LEFTMOUSE:
2371                         if (event->val == KM_RELEASE)
2372                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2373                         retval = WM_UI_HANDLER_BREAK;
2374                         break;
2375         }
2376
2377         if (retval == WM_UI_HANDLER_BREAK) {
2378                 ui_check_but(but);
2379                 ED_region_tag_redraw(data->region);
2380         }
2381 }
2382
2383 /* ************* number editing for various types ************* */
2384
2385 static void ui_numedit_begin(uiBut *but, uiHandleButtonData *data)
2386 {
2387         if (but->type == BUT_CURVE) {
2388                 but->editcumap = (CurveMapping *)but->poin;
2389         }
2390         else if (but->type == BUT_COLORBAND) {
2391                 data->coba = (ColorBand *)but->poin;
2392                 but->editcoba = data->coba;
2393         }
2394         else if (ELEM4(but->type, BUT_NORMAL, HSVCUBE, HSVCIRCLE, COLOR)) {
2395                 ui_get_but_vectorf(but, data->origvec);
2396                 copy_v3_v3(data->vec, data->origvec);
2397                 but->editvec = data->vec;
2398         }
2399         else {
2400                 float softrange, softmin, softmax;
2401
2402                 data->startvalue = ui_get_but_val(but);
2403                 data->origvalue = data->startvalue;
2404                 data->value = data->origvalue;
2405                 but->editval = &data->value;
2406
2407                 softmin = but->softmin;
2408                 softmax = but->softmax;
2409                 softrange = softmax - softmin;
2410
2411                 data->dragfstart = (softrange == 0.0f) ? 0.0f : ((float)data->value - softmin) / softrange;
2412                 data->dragf = data->dragfstart;
2413         }
2414
2415         data->dragchange = false;
2416         data->draglock = true;
2417 }
2418
2419 static void ui_numedit_end(uiBut *but, uiHandleButtonData *data)
2420 {
2421         but->editval = NULL;
2422         but->editvec = NULL;
2423         but->editcoba = NULL;
2424         but->editcumap = NULL;
2425
2426         data->dragstartx = 0;
2427         data->draglastx = 0;
2428         data->dragchange = false;
2429         data->dragcbd = NULL;
2430         data->dragsel = 0;
2431 }
2432
2433 static void ui_numedit_apply(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
2434 {
2435         if (data->interactive) {
2436                 ui_apply_button(C, block, but, data, true);
2437         }
2438         else {
2439                 ui_check_but(but);
2440         }
2441
2442         ED_region_tag_redraw(data->region);
2443 }
2444
2445 /* ****************** menu opening for various types **************** */
2446
2447 static void ui_blockopen_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2448 {
2449         uiBlockCreateFunc func = NULL;
2450         uiBlockHandleCreateFunc handlefunc = NULL;
2451         uiMenuCreateFunc menufunc = NULL;
2452         char *menustr = NULL;
2453         void *arg = NULL;
2454
2455         switch (but->type) {
2456                 case BLOCK:
2457                 case PULLDOWN:
2458                         if (but->menu_create_func) {
2459                                 menufunc = but->menu_create_func;
2460                                 arg = but->poin;
2461                         }
2462                         else {
2463                                 func = but->block_create_func;
2464                                 arg = but->poin ? but->poin : but->func_argN;
2465                         }
2466                         break;
2467                 case MENU:
2468                         if (but->menu_create_func) {
2469                                 menufunc = but->menu_create_func;
2470                                 arg = but->poin;
2471                         }
2472                         else {
2473                                 data->origvalue = ui_get_but_val(but);
2474                                 data->value = data->origvalue;
2475                                 but->editval = &data->value;
2476
2477                                 menustr = but->str;
2478                         }
2479                         break;
2480                 case ICONROW:
2481                         menufunc = ui_block_func_ICONROW;
2482                         arg = but;
2483                         break;
2484                 case ICONTEXTROW:
2485                         menufunc = ui_block_func_ICONTEXTROW;
2486                         arg = but;
2487                         break;
2488                 case COLOR:
2489                         ui_get_but_vectorf(but, data->origvec);
2490                         copy_v3_v3(data->vec, data->origvec);
2491                         but->editvec = data->vec;
2492
2493                         handlefunc = ui_block_func_COLOR;
2494                         arg = but;
2495                         break;
2496
2497                         /* quiet warnings for unhandled types */
2498                 default:
2499                         break;
2500         }
2501
2502         if (func || handlefunc) {
2503                 data->menu = ui_popup_block_create(C, data->region, but, func, handlefunc, arg);
2504                 if (but->block->handle)
2505                         data->menu->popup = but->block->handle->popup;
2506         }
2507         else if (menufunc || menustr) {
2508                 data->menu = ui_popup_menu_create(C, data->region, but, menufunc, arg, menustr);
2509                 if (but->block->handle)
2510                         data->menu->popup = but->block->handle->popup;
2511         }
2512
2513         /* this makes adjacent blocks auto open from now on */
2514         //if (but->block->auto_open == 0) but->block->auto_open = 1;
2515 }
2516
2517 static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2518 {
2519         if (but) {
2520                 but->editval = NULL;
2521                 but->editvec = NULL;
2522
2523                 but->block->auto_open_last = PIL_check_seconds_timer();
2524         }
2525
2526         if (data->menu) {
2527                 ui_popup_block_free(C, data->menu);
2528                 data->menu = NULL;
2529         }
2530 }
2531
2532 int ui_button_open_menu_direction(uiBut *but)
2533 {
2534         uiHandleButtonData *data = but->active;
2535
2536         if (data && data->menu)
2537                 return data->menu->direction;
2538         
2539         return 0;
2540 }
2541
2542 /* ***************** events for different button types *************** */
2543
2544 static int ui_do_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2545 {
2546         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2547                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2548                         button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE);
2549                         return WM_UI_HANDLER_BREAK;
2550                 }
2551                 else if (event->type == LEFTMOUSE && but->block->handle) {
2552                         /* regular buttons will be 'UI_SELECT', menu items 'UI_ACTIVE' */
2553                         if (!(but->flag & (UI_SELECT | UI_ACTIVE)))
2554                                 data->cancel = true;
2555                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2556                         return WM_UI_HANDLER_BREAK;
2557                 }
2558                 else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
2559                         button_activate_state(C, but, BUTTON_STATE_WAIT_FLASH);
2560                         return WM_UI_HANDLER_BREAK;
2561                 }
2562         }
2563         else if (data->state == BUTTON_STATE_WAIT_RELEASE) {
2564                 if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
2565                         if (!(but->flag & UI_SELECT))
2566                                 data->cancel = true;
2567                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2568                         return WM_UI_HANDLER_BREAK;
2569                 }
2570         }
2571
2572         return WM_UI_HANDLER_CONTINUE;
2573 }
2574
2575 static int ui_do_but_HOTKEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2576 {
2577         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2578                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2579                         but->drawstr[0] = 0;
2580                         but->modifier_key = 0;
2581                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2582                         return WM_UI_HANDLER_BREAK;
2583                 }
2584         }
2585         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2586                 
2587                 if (event->type == MOUSEMOVE)
2588                         return WM_UI_HANDLER_CONTINUE;
2589                 
2590                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2591                         /* only cancel if click outside the button */
2592                         if (ui_mouse_inside_button(but->active->region, but, event->x, event->y) == 0) {
2593                                 /* data->cancel doesnt work, this button opens immediate */
2594                                 if (but->flag & UI_BUT_IMMEDIATE)
2595                                         ui_set_but_val(but, 0);
2596                                 else
2597                                         data->cancel = true;
2598                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2599                                 return WM_UI_HANDLER_BREAK;
2600                         }
2601                 }
2602                 
2603                 /* always set */
2604                 but->modifier_key = 0;
2605                 if (event->shift) but->modifier_key |= KM_SHIFT;
2606                 if (event->alt) but->modifier_key |= KM_ALT;
2607                 if (event->ctrl) but->modifier_key |= KM_CTRL;
2608                 if (event->oskey) but->modifier_key |= KM_OSKEY;
2609
2610                 ui_check_but(but);
2611                 ED_region_tag_redraw(data->region);
2612                         
2613                 if (event->val == KM_PRESS) {
2614                         if (ISHOTKEY(event->type)) {
2615                                 
2616                                 if (WM_key_event_string(event->type)[0])
2617                                         ui_set_but_val(but, event->type);
2618                                 else
2619                                         data->cancel = true;
2620                                 
2621                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2622                                 return WM_UI_HANDLER_BREAK;
2623                         }
2624                         else if (event->type == ESCKEY) {
2625                                 data->cancel = true;
2626                                 data->escapecancel = true;
2627                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2628                         }
2629                         
2630                 }
2631         }
2632         
2633         return WM_UI_HANDLER_CONTINUE;
2634 }
2635
2636 static int ui_do_but_KEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2637 {
2638         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2639                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2640                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2641                         return WM_UI_HANDLER_BREAK;
2642                 }
2643         }
2644         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2645                 if (event->type == MOUSEMOVE)
2646                         return WM_UI_HANDLER_CONTINUE;
2647
2648                 if (event->val == KM_PRESS) {
2649                         if (WM_key_event_string(event->type)[0])
2650                                 ui_set_but_val(but, event->type);
2651                         else
2652                                 data->cancel = true;
2653
2654                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2655                 }
2656         }
2657
2658         return WM_UI_HANDLER_CONTINUE;
2659 }
2660
2661 static int ui_do_but_TEX(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2662 {
2663         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2664                 if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2665                         if (but->dt == UI_EMBOSSN && !event->ctrl) {
2666                                 /* pass */
2667                         }
2668                         else {
2669                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2670                                 return WM_UI_HANDLER_BREAK;
2671                         }
2672                 }
2673         }
2674         else if (data->state == BUTTON_STATE_TEXT_EDITING) {
2675                 ui_do_but_textedit(C, block, but, data, event);
2676                 return WM_UI_HANDLER_BREAK;
2677         }
2678         else if (data->state == BUTTON_STATE_TEXT_SELECTING) {
2679                 ui_do_but_textedit_select(C, block, but, data, event);
2680                 return WM_UI_HANDLER_BREAK;
2681         }
2682
2683         return WM_UI_HANDLER_CONTINUE;
2684 }
2685
2686 static int ui_do_but_SEARCH_UNLINK(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2687 {
2688         /* unlink icon is on right */
2689         if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2690                 ARegion *ar = data->region;
2691                 rcti rect;
2692                 int x = event->x, y = event->y;
2693                 
2694                 ui_window_to_block(ar, but->block, &x, &y);
2695                 
2696                 BLI_rcti_rctf_copy(&rect, &but->rect);
2697                 
2698                 rect.xmin = rect.xmax - (BLI_rcti_size_y(&rect));
2699                 if ( BLI_rcti_isect_pt(&rect, x, y) ) {
2700                         /* most likely NULL, but let's check, and give it temp zero string */
2701                         if (data->str == NULL)
2702                                 data->str = MEM_callocN(16, "temp str");
2703                         data->str[0] = 0;
2704                         
2705                         ui_apply_but_TEX(C, but, data);
2706                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2707                         
2708                         return WM_UI_HANDLER_BREAK;
2709                 }
2710         }
2711         return ui_do_but_TEX(C, block, but, data, event);
2712 }
2713
2714 static int ui_do_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2715 {
2716 #ifdef USE_DRAG_TOGGLE
2717         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2718                 if (event->type == LEFTMOUSE && event->val == KM_PRESS && ui_is_but_bool(but)) {
2719                         data->togdual = event->ctrl;
2720                         data->togonly = !event->shift;
2721                         ui_apply_button(C, but->block, but, data, true);
2722                         button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2723                         data->dragstartx = event->x;
2724                         data->dragstarty = event->y;
2725                         return WM_UI_HANDLER_BREAK;
2726                 }
2727         }
2728         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2729                 /* note: the 'BUTTON_STATE_WAIT_DRAG' part of 'ui_do_but_EXIT' could be refactored into its own function */
2730                 data->applied = false;
2731                 return ui_do_but_EXIT(C, but, data, event);
2732         }
2733 #endif
2734         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2735                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2736                         data->togdual = event->ctrl;
2737                         data->togonly = !event->shift;
2738                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2739                         return WM_UI_HANDLER_BREAK;
2740                 }
2741         }
2742         return WM_UI_HANDLER_CONTINUE;
2743 }
2744
2745 static int ui_do_but_EXIT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2746 {
2747         
2748         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2749
2750                 /* first handle click on icondrag type button */
2751                 if (event->type == LEFTMOUSE && but->dragpoin) {
2752                         if (ui_but_mouse_inside_icon(but, data->region, event)) {
2753                                 
2754                                 /* tell the button to wait and keep checking further events to
2755                                  * see if it should start dragging */
2756                                 button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2757                                 data->dragstartx = event->x;
2758                                 data->dragstarty = event->y;
2759                                 return WM_UI_HANDLER_CONTINUE;
2760                         }
2761                 }
2762 #ifdef USE_DRAG_TOGGLE
2763                 if (event->type == LEFTMOUSE && ui_is_but_bool(but)) {
2764                         button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2765                         data->dragstartx = event->x;
2766                         data->dragstarty = event->y;
2767                         return WM_UI_HANDLER_CONTINUE;
2768                 }
2769 #endif
2770
2771                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2772                         int ret = WM_UI_HANDLER_BREAK;
2773                         /* XXX (a bit ugly) Special case handling for filebrowser drag button */
2774                         if (but->dragpoin && but->imb && ui_but_mouse_inside_icon(but, data->region, event)) {
2775                                 ret = WM_UI_HANDLER_CONTINUE;
2776                         }
2777                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2778                         return ret;
2779                 }
2780         }
2781         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2782                 
2783                 /* this function also ends state */
2784                 if (ui_but_start_drag(C, but, data, event)) {
2785                         return WM_UI_HANDLER_BREAK;
2786                 }
2787                 
2788                 /* If the mouse has been pressed and released, getting to 
2789                  * this point without triggering a drag, then clear the 
2790                  * drag state for this button and continue to pass on the event */
2791                 if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2792                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2793                         return WM_UI_HANDLER_CONTINUE;
2794                 }
2795                 
2796                 /* while waiting for a drag to be triggered, always block 
2797                  * other events from getting handled */
2798                 return WM_UI_HANDLER_BREAK;
2799         }
2800         
2801         return WM_UI_HANDLER_CONTINUE;
2802 }
2803
2804 /* var names match ui_numedit_but_NUM */
2805 static float ui_numedit_apply_snapf(uiBut *but, float tempf, float softmin, float softmax, float softrange, int snap)
2806 {
2807         if (tempf == softmin || tempf == softmax || snap == 0) {
2808                 /* pass */
2809         }
2810         else {
2811                 float fac = 1.0f;
2812                 
2813                 if (ui_is_but_unit(but)) {
2814                         UnitSettings *unit = but->block->unit;
2815                         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
2816
2817                         if (bUnit_IsValid(unit->system, unit_type)) {
2818                                 fac = (float)bUnit_BaseScalar(unit->system, unit_type);
2819                                 if (ELEM3(unit_type, B_UNIT_LENGTH, B_UNIT_AREA, B_UNIT_VOLUME)) {
2820                                         fac /= unit->scale_length;
2821                                 }
2822                         }
2823                 }
2824
2825                 if (fac != 1.0f) {
2826                         /* snap in unit-space */
2827                         tempf /= fac;
2828                         /* softmin /= fac; */ /* UNUSED */
2829                         /* softmax /= fac; */ /* UNUSED */
2830                         softrange /= fac;
2831                 }
2832
2833                 if (snap == 1) {
2834                         if      (softrange < 2.10f) tempf = 0.1f  * floorf(10.0f * tempf);
2835                         else if (softrange < 21.0f) tempf = floorf(tempf);
2836                         else                        tempf = 10.0f * floorf(tempf / 10.0f);
2837                 }
2838                 else if (snap == 2) {
2839                         if      (softrange < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
2840                         else if (softrange < 21.0f) tempf = 0.1f  * floorf(10.0f * tempf);
2841                         else                        tempf = floor(tempf);
2842                 }
2843                 
2844                 if (fac != 1.0f)
2845                         tempf *= fac;
2846         }
2847
2848         return tempf;
2849 }
2850
2851 static float ui_numedit_apply_snap(int temp, float softmin, float softmax, int snap)
2852 {
2853         if (temp == softmin || temp == softmax)
2854                 return temp;
2855
2856         switch (snap) {
2857                 case 0:
2858                         break;
2859                 case 1:
2860                         temp = 10 * (temp / 10);
2861                         break;
2862                 case 2:
2863                         temp = 100 * (temp / 100);
2864                         break;
2865         }
2866
2867         return temp;
2868 }
2869
2870 static bool ui_numedit_but_NUM(uiBut *but, uiHandleButtonData *data, float fac, int snap, int mx)
2871 {
2872         float deler, tempf, softmin, softmax, softrange;
2873         int lvalue, temp;
2874         bool changed = false;
2875         const bool is_float = ui_is_but_float(but);
2876         
2877         if (mx == data->draglastx)
2878                 return changed;
2879         
2880         /* drag-lock - prevent unwanted scroll adjustments */
2881         /* change value (now 3) to adjust threshold in pixels */
2882         if (data->draglock) {
2883                 if (abs(mx - data->dragstartx) <= 3)
2884                         return changed;
2885
2886                 data->draglock = false;
2887                 data->dragstartx = mx;  /* ignore mouse movement within drag-lock */
2888         }
2889
2890         softmin = but->softmin;
2891         softmax = but->softmax;
2892         softrange = softmax - softmin;
2893
2894         if (ui_is_a_warp_but(but)) {
2895                 /* Mouse location isn't screen clamped to the screen so use a linear mapping
2896                  * 2px == 1-int, or 1px == 1-ClickStep */
2897                 if (is_float) {
2898                         fac *= 0.01f * but->a1;
2899                         tempf = (float)data->startvalue + ((float)(mx - data->dragstartx) * fac);
2900                         tempf = ui_numedit_apply_snapf(but, tempf, softmin, softmax, softrange, snap);
2901
2902 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2903                         if (tempf < softmin) {
2904                                 data->dragstartx -= (softmin - tempf) / fac;
2905                                 tempf = softmin;
2906                         }
2907                         else if (tempf > softmax) {
2908                                 data->dragstartx += (tempf - softmax) / fac;
2909                                 tempf = softmax;
2910                         }
2911 #else
2912                         CLAMP(tempf, softmin, softmax);
2913 #endif
2914
2915                         if (tempf != (float)data->value) {
2916                                 data->dragchange = true;
2917                                 data->value = tempf;
2918                                 changed = true;
2919                         }
2920                 }
2921                 else {
2922                         if      (softrange > 256) fac = 1.0;        /* 1px == 1 */
2923                         else if (softrange >  32) fac = 1.0 / 2.0;  /* 2px == 1 */
2924                         else                      fac = 1.0 / 16.0; /* 16px == 1? */
2925
2926                         temp = data->startvalue + (((double)mx - data->dragstartx) * (double)fac);
2927                         temp = ui_numedit_apply_snap(temp, softmin, softmax, snap);
2928
2929 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2930                         if (temp < softmin) {
2931                                 data->dragstartx -= (softmin - temp) / fac;
2932                                 temp = softmin;
2933