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