RNA: Add check_existing arg to other load() funcs
[blender.git] / source / blender / blenkernel / intern / font.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/font.c
29  *  \ingroup bke
30  */
31
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <math.h>
36 #include <stdlib.h>
37 #include <wchar.h>
38 #include <wctype.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "BLI_utildefines.h"
43 #include "BLI_path_util.h"
44 #include "BLI_listbase.h"
45 #include "BLI_ghash.h"
46 #include "BLI_string.h"
47 #include "BLI_string_utf8.h"
48 #include "BLI_math.h"
49 #include "BLI_threads.h"
50 #include "BLI_vfontdata.h"
51
52 #include "DNA_packedFile_types.h"
53 #include "DNA_curve_types.h"
54 #include "DNA_vfont_types.h"
55 #include "DNA_object_types.h"
56
57 #include "BKE_packedFile.h"
58 #include "BKE_library.h"
59 #include "BKE_font.h"
60 #include "BKE_global.h"
61 #include "BKE_main.h"
62 #include "BKE_anim.h"
63 #include "BKE_curve.h"
64
65 static ThreadRWMutex vfont_rwlock = BLI_RWLOCK_INITIALIZER;
66
67 /* The vfont code */
68 void BKE_vfont_free_data(struct VFont *vfont)
69 {
70         if (vfont->data) {
71                 if (vfont->data->characters) {
72                         GHashIterator gh_iter;
73                         GHASH_ITER (gh_iter, vfont->data->characters) {
74                                 VChar *che = BLI_ghashIterator_getValue(&gh_iter);
75
76                                 while (che->nurbsbase.first) {
77                                         Nurb *nu = che->nurbsbase.first;
78                                         if (nu->bezt) MEM_freeN(nu->bezt);
79                                         BLI_freelinkN(&che->nurbsbase, nu);
80                                 }
81
82                                 MEM_freeN(che);
83                         }
84
85                         BLI_ghash_free(vfont->data->characters, NULL, NULL);
86                 }
87
88                 MEM_freeN(vfont->data);
89                 vfont->data = NULL;
90         }
91
92         if (vfont->temp_pf) {
93                 freePackedFile(vfont->temp_pf);  /* NULL when the font file can't be found on disk */
94                 vfont->temp_pf = NULL;
95         }
96 }
97
98 void BKE_vfont_free(struct VFont *vf)
99 {
100         if (vf == NULL) return;
101
102         BKE_vfont_free_data(vf);
103
104         if (vf->packedfile) {
105                 freePackedFile(vf->packedfile);
106                 vf->packedfile = NULL;
107         }
108 }
109
110 static void *builtin_font_data = NULL;
111 static int builtin_font_size = 0;
112
113 bool BKE_vfont_is_builtin(struct VFont *vfont)
114 {
115         return STREQ(vfont->name, FO_BUILTIN_NAME);
116 }
117
118 void BKE_vfont_builtin_register(void *mem, int size)
119 {
120         builtin_font_data = mem;
121         builtin_font_size = size;
122 }
123
124 static PackedFile *get_builtin_packedfile(void)
125 {
126         if (!builtin_font_data) {
127                 printf("Internal error, builtin font not loaded\n");
128
129                 return NULL;
130         }
131         else {
132                 void *mem = MEM_mallocN(builtin_font_size, "vfd_builtin");
133
134                 memcpy(mem, builtin_font_data, builtin_font_size);
135         
136                 return newPackedFileMemory(mem, builtin_font_size);
137         }
138 }
139
140 static VFontData *vfont_get_data(Main *bmain, VFont *vfont)
141 {
142         if (vfont == NULL) {
143                 return NULL;
144         }
145
146         /* And then set the data */
147         if (!vfont->data) {
148                 PackedFile *pf;
149
150                 BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_WRITE);
151
152                 if (vfont->data) {
153                         /* Check data again, since it might have been already
154                          * initialized from other thread (previous check is
155                          * not accurate or threading, just prevents unneeded
156                          * lock if all the data is here for sure).
157                          */
158                         BLI_rw_mutex_unlock(&vfont_rwlock);
159                         return vfont->data;
160                 }
161
162                 if (BKE_vfont_is_builtin(vfont)) {
163                         pf = get_builtin_packedfile();
164                 }
165                 else {
166                         if (vfont->packedfile) {
167                                 pf = vfont->packedfile;
168
169                                 /* We need to copy a tmp font to memory unless it is already there */
170                                 if (vfont->temp_pf == NULL) {
171                                         vfont->temp_pf = dupPackedFile(pf);
172                                 }
173                         }
174                         else {
175                                 pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id));
176
177                                 if (vfont->temp_pf == NULL) {
178                                         vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id));
179                                 }
180                         }
181                         if (!pf) {
182                                 printf("Font file doesn't exist: %s\n", vfont->name);
183
184                                 /* DON'T DO THIS
185                                  * missing file shouldn't modify path! - campbell */
186 #if 0
187                                 strcpy(vfont->name, FO_BUILTIN_NAME);
188 #endif
189                                 pf = get_builtin_packedfile();
190                         }
191                 }
192                 
193                 if (pf) {
194                         vfont->data = BLI_vfontdata_from_freetypefont(pf);
195                         if (pf != vfont->packedfile) {
196                                 freePackedFile(pf);
197                         }
198                 }
199
200                 BLI_rw_mutex_unlock(&vfont_rwlock);
201         }
202
203         return vfont->data;
204 }
205
206 VFont *BKE_vfont_load(Main *bmain, const char *filepath)
207 {
208         char filename[FILE_MAXFILE];
209         VFont *vfont = NULL;
210         PackedFile *pf;
211         PackedFile *temp_pf = NULL;
212         bool is_builtin;
213         
214         if (STREQ(filepath, FO_BUILTIN_NAME)) {
215                 BLI_strncpy(filename, filepath, sizeof(filename));
216                 
217                 pf = get_builtin_packedfile();
218                 is_builtin = true;
219         }
220         else {
221                 BLI_split_file_part(filepath, filename, sizeof(filename));
222                 pf = newPackedFile(NULL, filepath, bmain->name);
223                 temp_pf = newPackedFile(NULL, filepath, bmain->name);
224                 
225                 is_builtin = false;
226         }
227
228         if (pf) {
229                 VFontData *vfd;
230
231                 vfd = BLI_vfontdata_from_freetypefont(pf);
232                 if (vfd) {
233                         vfont = BKE_libblock_alloc(bmain, ID_VF, filename);
234                         vfont->data = vfd;
235
236                         /* if there's a font name, use it for the ID name */
237                         if (vfd->name[0] != '\0') {
238                                 BLI_strncpy(vfont->id.name + 2, vfd->name, sizeof(vfont->id.name) - 2);
239                         }
240                         BLI_strncpy(vfont->name, filepath, sizeof(vfont->name));
241
242                         /* if autopack is on store the packedfile in de font structure */
243                         if (!is_builtin && (G.fileflags & G_AUTOPACK)) {
244                                 vfont->packedfile = pf;
245                         }
246
247                         /* Do not add FO_BUILTIN_NAME to temporary listbase */
248                         if (!STREQ(filename, FO_BUILTIN_NAME)) {
249                                 vfont->temp_pf = temp_pf;
250                         }
251                 }
252
253                 /* Free the packed file */
254                 if (!vfont || vfont->packedfile != pf) {
255                         freePackedFile(pf);
256                 }
257         }
258         
259         return vfont;
260 }
261
262 VFont *BKE_vfont_load_exists_ex(struct Main *bmain, const char *filepath, bool *r_exists)
263 {
264         VFont *vfont;
265         char str[FILE_MAX], strtest[FILE_MAX];
266
267         BLI_strncpy(str, filepath, sizeof(str));
268         BLI_path_abs(str, bmain->name);
269
270         /* first search an identical filepath */
271         for (vfont = bmain->vfont.first; vfont; vfont = vfont->id.next) {
272                 BLI_strncpy(strtest, vfont->name, sizeof(vfont->name));
273                 BLI_path_abs(strtest, ID_BLEND_PATH(bmain, &vfont->id));
274
275                 if (BLI_path_cmp(strtest, str) == 0) {
276                         vfont->id.us++;  /* officially should not, it doesn't link here! */
277                         if (r_exists)
278                                 *r_exists = true;
279                         return vfont;
280                 }
281         }
282
283         if (r_exists)
284                 *r_exists = false;
285         return BKE_vfont_load(bmain, filepath);
286 }
287
288 VFont *BKE_vfont_load_exists(struct Main *bmain, const char *filepath)
289 {
290         return BKE_vfont_load_exists_ex(bmain, filepath, NULL);
291 }
292
293 static VFont *which_vfont(Curve *cu, CharInfo *info)
294 {
295         switch (info->flag & (CU_CHINFO_BOLD | CU_CHINFO_ITALIC)) {
296                 case CU_CHINFO_BOLD:
297                         return cu->vfontb ? cu->vfontb : cu->vfont;
298                 case CU_CHINFO_ITALIC:
299                         return cu->vfonti ? cu->vfonti : cu->vfont;
300                 case (CU_CHINFO_BOLD | CU_CHINFO_ITALIC):
301                         return cu->vfontbi ? cu->vfontbi : cu->vfont;
302                 default:
303                         return cu->vfont;
304         }
305 }
306
307 VFont *BKE_vfont_builtin_get(void)
308 {
309         VFont *vfont;
310         
311         for (vfont = G.main->vfont.first; vfont; vfont = vfont->id.next) {
312                 if (BKE_vfont_is_builtin(vfont)) {
313                         return vfont;
314                 }
315         }
316         
317         return BKE_vfont_load(G.main, FO_BUILTIN_NAME);
318 }
319
320 static VChar *find_vfont_char(VFontData *vfd, unsigned int character)
321 {
322         return BLI_ghash_lookup(vfd->characters, SET_UINT_IN_POINTER(character));
323 }
324
325 static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect,
326                             float yofs, float rot, int charidx, short mat_nr)
327 {
328         Nurb *nu2;
329         BPoint *bp;
330         
331         nu2 = (Nurb *) MEM_callocN(sizeof(Nurb), "underline_nurb");
332         nu2->resolu = cu->resolu;
333         nu2->bezt = NULL;
334         nu2->knotsu = nu2->knotsv = NULL;
335         nu2->flag = CU_2D;
336         nu2->charidx = charidx + 1000;
337         if (mat_nr > 0) nu2->mat_nr = mat_nr - 1;
338         nu2->pntsu = 4;
339         nu2->pntsv = 1;
340         nu2->orderu = 4;
341         nu2->orderv = 1;
342         nu2->flagu = CU_NURB_CYCLIC;
343
344         bp = (BPoint *)MEM_callocN(4 * sizeof(BPoint), "underline_bp");
345
346         copy_v4_fl4(bp[0].vec, rect->xmin, (rect->ymax + yofs), 0.0f, 1.0f);
347         copy_v4_fl4(bp[1].vec, rect->xmax, (rect->ymax + yofs), 0.0f, 1.0f);
348         copy_v4_fl4(bp[2].vec, rect->xmax, (rect->ymin + yofs), 0.0f, 1.0f);
349         copy_v4_fl4(bp[3].vec, rect->xmin, (rect->ymin + yofs), 0.0f, 1.0f);
350
351         nu2->bp = bp;
352         BLI_addtail(nubase, nu2);
353
354         if (rot != 0.0f) {
355                 float si, co;
356                 int i;
357
358                 si = sinf(rot);
359                 co = cosf(rot);
360
361                 for (i = nu2->pntsu; i > 0; i--) {
362                         float *fp;
363                         float x, y;
364
365                         fp = bp->vec;
366
367                         x = fp[0] - rect->xmin;
368                         y = fp[1] - rect->ymin;
369
370                         fp[0] = (+co * x + si * y) + rect->xmin;
371                         fp[1] = (-si * x + co * y) + rect->ymin;
372
373                         bp++;
374                 }
375
376                 bp = nu2->bp;
377         }
378
379         mul_v2_fl(bp[0].vec, cu->fsize);
380         mul_v2_fl(bp[1].vec, cu->fsize);
381         mul_v2_fl(bp[2].vec, cu->fsize);
382         mul_v2_fl(bp[3].vec, cu->fsize);
383 }
384
385 static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info,
386                       float ofsx, float ofsy, float rot, int charidx)
387 {
388         BezTriple *bezt1, *bezt2;
389         Nurb *nu1 = NULL, *nu2 = NULL;
390         float *fp, fsize, shear, x, si, co;
391         VFontData *vfd = NULL;
392         VChar *che = NULL;
393         int i;
394
395         vfd = vfont_get_data(bmain, which_vfont(cu, info));
396         if (!vfd) return;
397
398 #if 0
399         if (cu->selend < cu->selstart) {
400                 if ((charidx >= (cu->selend)) && (charidx <= (cu->selstart - 2)))
401                         sel = 1;
402         }
403         else {
404                 if ((charidx >= (cu->selstart - 1)) && (charidx <= (cu->selend - 1)))
405                         sel = 1;
406         }
407 #endif
408
409         /* make a copy at distance ofsx, ofsy with shear */
410         fsize = cu->fsize;
411         shear = cu->shear;
412         si = sinf(rot);
413         co = cosf(rot);
414
415         che = find_vfont_char(vfd, character);
416         
417         /* Select the glyph data */
418         if (che)
419                 nu1 = che->nurbsbase.first;
420
421         /* Create the character */
422         while (nu1) {
423                 bezt1 = nu1->bezt;
424                 if (bezt1) {
425                         nu2 = (Nurb *) MEM_mallocN(sizeof(Nurb), "duplichar_nurb");
426                         if (nu2 == NULL) break;
427                         memcpy(nu2, nu1, sizeof(struct Nurb));
428                         nu2->resolu = cu->resolu;
429                         nu2->bp = NULL;
430                         nu2->knotsu = nu2->knotsv = NULL;
431                         nu2->flag = CU_SMOOTH;
432                         nu2->charidx = charidx;
433                         if (info->mat_nr > 0) {
434                                 nu2->mat_nr = info->mat_nr - 1;
435                         }
436                         else {
437                                 nu2->mat_nr = 0;
438                         }
439                         /* nu2->trim.first = 0; */
440                         /* nu2->trim.last = 0; */
441                         i = nu2->pntsu;
442
443                         bezt2 = (BezTriple *)MEM_mallocN(i * sizeof(BezTriple), "duplichar_bezt2");
444                         if (bezt2 == NULL) {
445                                 MEM_freeN(nu2);
446                                 break;
447                         }
448                         memcpy(bezt2, bezt1, i * sizeof(struct BezTriple));
449                         nu2->bezt = bezt2;
450                         
451                         if (shear != 0.0f) {
452                                 bezt2 = nu2->bezt;
453                                 
454                                 for (i = nu2->pntsu; i > 0; i--) {
455                                         bezt2->vec[0][0] += shear * bezt2->vec[0][1];
456                                         bezt2->vec[1][0] += shear * bezt2->vec[1][1];
457                                         bezt2->vec[2][0] += shear * bezt2->vec[2][1];
458                                         bezt2++;
459                                 }
460                         }
461                         if (rot != 0.0f) {
462                                 bezt2 = nu2->bezt;
463                                 for (i = nu2->pntsu; i > 0; i--) {
464                                         fp = bezt2->vec[0];
465
466                                         x = fp[0];
467                                         fp[0] = co * x + si * fp[1];
468                                         fp[1] = -si * x + co * fp[1];
469                                         x = fp[3];
470                                         fp[3] = co * x + si * fp[4];
471                                         fp[4] = -si * x + co * fp[4];
472                                         x = fp[6];
473                                         fp[6] = co * x + si * fp[7];
474                                         fp[7] = -si * x + co * fp[7];
475
476                                         bezt2++;
477                                 }
478                         }
479                         bezt2 = nu2->bezt;
480
481                         if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
482                                 const float sca = cu->smallcaps_scale;
483                                 for (i = nu2->pntsu; i > 0; i--) {
484                                         fp = bezt2->vec[0];
485                                         fp[0] *= sca;
486                                         fp[1] *= sca;
487                                         fp[3] *= sca;
488                                         fp[4] *= sca;
489                                         fp[6] *= sca;
490                                         fp[7] *= sca;
491                                         bezt2++;
492                                 }
493                         }
494                         bezt2 = nu2->bezt;
495
496                         for (i = nu2->pntsu; i > 0; i--) {
497                                 fp = bezt2->vec[0];
498                                 fp[0] = (fp[0] + ofsx) * fsize;
499                                 fp[1] = (fp[1] + ofsy) * fsize;
500                                 fp[3] = (fp[3] + ofsx) * fsize;
501                                 fp[4] = (fp[4] + ofsy) * fsize;
502                                 fp[6] = (fp[6] + ofsx) * fsize;
503                                 fp[7] = (fp[7] + ofsy) * fsize;
504                                 bezt2++;
505                         }
506                         
507                         BLI_addtail(nubase, nu2);
508                 }
509                 
510                 nu1 = nu1->next;
511         }
512 }
513
514 int BKE_vfont_select_get(Object *ob, int *r_start, int *r_end)
515 {
516         Curve *cu = ob->data;
517         EditFont *ef = cu->editfont;
518         int start, end, direction;
519         
520         if ((ob->type != OB_FONT) || (ef == NULL)) return 0;
521
522         BLI_assert(ef->len >= 0);
523         BLI_assert(ef->selstart >= 0 && ef->selstart <= ef->len + 1);
524         BLI_assert(ef->selend   >= 0 && ef->selend   <= ef->len);
525         BLI_assert(ef->pos      >= 0 && ef->pos      <= ef->len);
526
527         if (ef->selstart == 0) {
528                 return 0;
529         }
530
531         if (ef->selstart <= ef->selend) {
532                 start = ef->selstart - 1;
533                 end = ef->selend - 1;
534                 direction = 1;
535         }
536         else {
537                 start = ef->selend;
538                 end = ef->selstart - 2;
539                 direction = -1;
540         }
541
542         if (start == end + 1) {
543                 return 0;
544         }
545         else {
546                 BLI_assert(start < end + 1);
547                 *r_start = start;
548                 *r_end = end;
549                 return direction;
550         }
551 }
552
553 void BKE_vfont_select_clamp(Object *ob)
554 {
555         Curve *cu = ob->data;
556         EditFont *ef = cu->editfont;
557
558         BLI_assert((ob->type == OB_FONT) && ef);
559
560         CLAMP_MAX(ef->pos,      ef->len);
561         CLAMP_MAX(ef->selstart, ef->len + 1);
562         CLAMP_MAX(ef->selend,   ef->len);
563 }
564
565 static float char_width(Curve *cu, VChar *che, CharInfo *info)
566 {
567         /* The character wasn't found, propably ascii = 0, then the width shall be 0 as well */
568         if (che == NULL) {
569                 return 0.0f;
570         }
571         else if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
572                 return che->width * cu->smallcaps_scale;
573         }
574         else {
575                 return che->width;
576         }
577 }
578
579 static void textbox_scale(TextBox *tb_dst, const TextBox *tb_src, float scale)
580 {
581         tb_dst->x = tb_src->x * scale;
582         tb_dst->y = tb_src->y * scale;
583         tb_dst->w = tb_src->w * scale;
584         tb_dst->h = tb_src->h * scale;
585 }
586
587 /**
588  * Used for storing per-line data for alignment & wrapping.
589  */
590 struct TempLineInfo {
591         float x_min;      /* left margin */
592         float x_max;      /* right margin */
593         int   char_nr;    /* number of characters */
594         int   wspace_nr;  /* number of whitespaces of line */
595 };
596
597 bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, int mode, ListBase *r_nubase,
598                            const wchar_t **r_text, int *r_text_len, bool *r_text_free,
599                            struct CharTrans **r_chartransdata)
600 {
601         Curve *cu = ob->data;
602         EditFont *ef = cu->editfont;
603         EditFontSelBox *selboxes = NULL;
604         VFont *vfont, *oldvfont;
605         VFontData *vfd = NULL;
606         CharInfo *info = NULL, *custrinfo;
607         TextBox tb_scale;
608         bool use_textbox;
609         VChar *che;
610         struct CharTrans *chartransdata = NULL, *ct;
611         struct TempLineInfo *lineinfo;
612         float *f, xof, yof, xtrax, linedist;
613         float twidth, maxlen = 0;
614         int i, slen, j;
615         int curbox;
616         int selstart, selend;
617         int cnr = 0, lnr = 0, wsnr = 0;
618         const wchar_t *mem;
619         wchar_t ascii;
620         bool ok = false;
621         const float xof_scale = cu->xof / cu->fsize;
622         const float yof_scale = cu->yof / cu->fsize;
623
624 #define MARGIN_X_MIN (xof_scale + tb_scale.x)
625 #define MARGIN_Y_MIN (yof_scale + tb_scale.y)
626
627         /* remark: do calculations including the trailing '\0' of a string
628          * because the cursor can be at that location */
629
630         BLI_assert(ob->type == OB_FONT);
631
632         /* Set font data */
633         vfont = cu->vfont;
634
635         if (cu->str == NULL) return ok;
636         if (vfont == NULL) return ok;
637
638         vfd = vfont_get_data(bmain, vfont);
639
640         /* The VFont Data can not be found */
641         if (!vfd) return ok;
642         
643         if (ef) {
644                 slen = ef->len;
645                 mem = ef->textbuf;
646                 custrinfo = ef->textbufinfo;
647         }
648         else {
649                 wchar_t *mem_tmp;
650                 slen = cu->len_wchar;
651
652                 /* Create unicode string */
653                 mem_tmp = MEM_mallocN(((slen + 1) * sizeof(wchar_t)), "convertedmem");
654
655                 BLI_strncpy_wchar_from_utf8(mem_tmp, cu->str, slen + 1);
656
657                 if (cu->strinfo == NULL) {  /* old file */
658                         cu->strinfo = MEM_callocN((slen + 4) * sizeof(CharInfo), "strinfo compat");
659                 }
660                 custrinfo = cu->strinfo;
661
662                 mem = mem_tmp;
663         }
664
665         if (cu->tb == NULL)
666                 cu->tb = MEM_callocN(MAXTEXTBOX * sizeof(TextBox), "TextBox compat");
667
668         if (ef) {
669                 if (ef->selboxes)
670                         MEM_freeN(ef->selboxes);
671
672                 if (BKE_vfont_select_get(ob, &selstart, &selend))
673                         ef->selboxes = MEM_callocN((selend - selstart + 1) * sizeof(EditFontSelBox), "font selboxes");
674                 else
675                         ef->selboxes = NULL;
676
677                 selboxes = ef->selboxes;
678         }
679
680         /* calc offset and rotation of each char */
681         ct = chartransdata = MEM_callocN((slen + 1) * sizeof(struct CharTrans), "buildtext");
682
683         /* We assume the worst case: 1 character per line (is freed at end anyway) */
684         lineinfo = MEM_mallocN(sizeof(*lineinfo) * (slen * 2 + 1), "lineinfo");
685         
686         linedist = cu->linedist;
687         
688         curbox = 0;
689         textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / cu->fsize);
690         use_textbox = (tb_scale.w != 0.0f);
691
692
693         xof = MARGIN_X_MIN;
694         yof = MARGIN_Y_MIN;
695
696         xtrax = 0.5f * cu->spacing - 0.5f;
697
698         oldvfont = NULL;
699
700         for (i = 0; i < slen; i++) {
701                 custrinfo[i].flag &= ~(CU_CHINFO_WRAP | CU_CHINFO_SMALLCAPS_CHECK);
702         }
703
704         for (i = 0; i <= slen; i++) {
705 makebreak:
706                 /* Characters in the list */
707                 info = &custrinfo[i];
708                 ascii = mem[i];
709                 if (info->flag & CU_CHINFO_SMALLCAPS) {
710                         ascii = towupper(ascii);
711                         if (mem[i] != ascii) {
712                                 info->flag |= CU_CHINFO_SMALLCAPS_CHECK;
713                         }
714                 }
715
716                 vfont = which_vfont(cu, info);
717
718                 if (vfont == NULL) break;
719
720                 if (vfont != oldvfont) {
721                         vfd = vfont_get_data(bmain, vfont);
722                         oldvfont = vfont;
723                 }
724
725                 /* VFont Data for VFont couldn't be found */
726                 if (!vfd) {
727                         MEM_freeN(chartransdata);
728                         chartransdata = NULL;
729                         MEM_freeN(lineinfo);
730                         goto finally;
731                 }
732
733                 if (!ELEM(ascii, '\n', '\0')) {
734                         BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_READ);
735                         che = find_vfont_char(vfd, ascii);
736                         BLI_rw_mutex_unlock(&vfont_rwlock);
737
738                         /*
739                          * The character wasn't in the current curve base so load it
740                          * But if the font is built-in then do not try loading since
741                          * whole font is in the memory already
742                          */
743                         if (che == NULL && BKE_vfont_is_builtin(vfont) == false) {
744                                 BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_WRITE);
745                                 /* Check it once again, char might have been already load
746                                  * between previous BLI_rw_mutex_unlock() and this BLI_rw_mutex_lock().
747                                  *
748                                  * Such a check should not be a bottleneck since it wouldn't
749                                  * happen often once all the chars are load.
750                                  */
751                                 if ((che = find_vfont_char(vfd, ascii)) == NULL) {
752                                         che = BLI_vfontchar_from_freetypefont(vfont, ascii);
753                                 }
754                                 BLI_rw_mutex_unlock(&vfont_rwlock);
755                         }
756                 }
757                 else {
758                         che = NULL;
759                 }
760
761                 twidth = char_width(cu, che, info);
762
763                 /* Calculate positions */
764                 if ((tb_scale.w != 0.0f) &&
765                     (ct->dobreak == 0) &&
766                     (((xof - tb_scale.x) + twidth) > xof_scale + tb_scale.w))
767                 {
768                         //              fprintf(stderr, "linewidth exceeded: %c%c%c...\n", mem[i], mem[i+1], mem[i+2]);
769                         for (j = i; j && (mem[j] != '\n') && (chartransdata[j].dobreak == 0); j--) {
770                                 if (mem[j] == ' ' || mem[j] == '-') {
771                                         ct -= (i - (j - 1));
772                                         cnr -= (i - (j - 1));
773                                         if (mem[j] == ' ') wsnr--;
774                                         if (mem[j] == '-') wsnr++;
775                                         i = j - 1;
776                                         xof = ct->xof;
777                                         ct[1].dobreak = 1;
778                                         custrinfo[i + 1].flag |= CU_CHINFO_WRAP;
779                                         goto makebreak;
780                                 }
781                                 if (chartransdata[j].dobreak) {
782                                         //                              fprintf(stderr, "word too long: %c%c%c...\n", mem[j], mem[j+1], mem[j+2]);
783                                         ct->dobreak = 1;
784                                         custrinfo[i + 1].flag |= CU_CHINFO_WRAP;
785                                         ct -= 1;
786                                         cnr -= 1;
787                                         i--;
788                                         xof = ct->xof;
789                                         goto makebreak;
790                                 }
791                         }
792                 }
793
794                 if (ascii == '\n' || ascii == 0 || ct->dobreak) {
795                         ct->xof = xof;
796                         ct->yof = yof;
797                         ct->linenr = lnr;
798                         ct->charnr = cnr;
799
800                         yof -= linedist;
801
802                         lineinfo[lnr].x_min     = (xof - xtrax) - tb_scale.x;
803                         lineinfo[lnr].x_max     = tb_scale.w;
804                         lineinfo[lnr].char_nr   = cnr;
805                         lineinfo[lnr].wspace_nr = wsnr;
806
807                         CLAMP_MIN(maxlen, lineinfo[lnr].x_min);
808
809                         if ((tb_scale.h != 0.0f) &&
810                             (cu->totbox > (curbox + 1)) &&
811                             ((-(yof - tb_scale.y)) > (tb_scale.h - linedist) - yof_scale))
812                         {
813                                 maxlen = 0;
814                                 curbox++;
815
816                                 textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / cu->fsize);
817
818                                 yof = MARGIN_Y_MIN;
819                         }
820
821                         /* XXX, has been unused for years, need to check if this is useful, r4613 r5282 - campbell */
822 #if 0
823                         if (ascii == '\n')
824                                 xof = xof_scale;
825                         else
826                                 xof = MARGIN_X_MIN;
827 #else
828                         xof = MARGIN_X_MIN;
829 #endif
830                         lnr++;
831                         cnr = 0;
832                         wsnr = 0;
833                 }
834                 else if (ascii == 9) {    /* TAB */
835                         float tabfac;
836                         
837                         ct->xof = xof;
838                         ct->yof = yof;
839                         ct->linenr = lnr;
840                         ct->charnr = cnr++;
841
842                         tabfac = (xof - MARGIN_X_MIN + 0.01f);
843                         tabfac = 2.0f * ceilf(tabfac / 2.0f);
844                         xof = MARGIN_X_MIN + tabfac;
845                 }
846                 else {
847                         EditFontSelBox *sb = NULL;
848                         float wsfac;
849
850                         ct->xof = xof;
851                         ct->yof = yof;
852                         ct->linenr = lnr;
853                         ct->charnr = cnr++;
854
855                         if (selboxes && (i >= selstart) && (i <= selend)) {
856                                 sb = &selboxes[i - selstart];
857                                 sb->y = yof * cu->fsize - linedist * cu->fsize * 0.1f;
858                                 sb->h = linedist * cu->fsize;
859                                 sb->w = xof * cu->fsize;
860                         }
861         
862                         if (ascii == 32) {
863                                 wsfac = cu->wordspace; 
864                                 wsnr++;
865                         }
866                         else {
867                                 wsfac = 1.0f;
868                         }
869                         
870                         /* Set the width of the character */
871                         twidth = char_width(cu, che, info);
872
873                         xof += (twidth * wsfac * (1.0f + (info->kern / 40.0f)) ) + xtrax;
874                         
875                         if (sb) {
876                                 sb->w = (xof * cu->fsize) - sb->w;
877                         }
878                 }
879                 ct++;
880         }
881         
882         cu->lines = 1;
883         for (i = 0; i <= slen; i++) {
884                 ascii = mem[i];
885                 ct = &chartransdata[i];
886                 if (ascii == '\n' || ct->dobreak) cu->lines++;
887         }
888
889         /* linedata is now: width of line */
890
891         if (cu->spacemode != CU_LEFT) {
892                 ct = chartransdata;
893
894                 if (cu->spacemode == CU_RIGHT) {
895                         struct TempLineInfo *li;
896
897                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
898                                 li->x_min = (li->x_max - li->x_min) + xof_scale;
899                         }
900
901                         for (i = 0; i <= slen; i++) {
902                                 ct->xof += lineinfo[ct->linenr].x_min;
903                                 ct++;
904                         }
905                 }
906                 else if (cu->spacemode == CU_MIDDLE) {
907                         struct TempLineInfo *li;
908
909                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
910                                 li->x_min = ((li->x_max - li->x_min) + xof_scale) / 2.0f;
911                         }
912
913                         for (i = 0; i <= slen; i++) {
914                                 ct->xof += lineinfo[ct->linenr].x_min;
915                                 ct++;
916                         }
917                 }
918                 else if ((cu->spacemode == CU_FLUSH) && use_textbox) {
919                         struct TempLineInfo *li;
920
921                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
922                                 li->x_min = ((li->x_max - li->x_min) + xof_scale);
923
924                                 if (li->char_nr > 1) {
925                                         li->x_min /= (float)(li->char_nr - 1);
926                                 }
927                         }
928                         for (i = 0; i <= slen; i++) {
929                                 for (j = i; (!ELEM(mem[j], '\0', '\n')) && (chartransdata[j].dobreak == 0) && (j < slen); j++) {
930                                         /* do nothing */
931                                 }
932
933 //                              if ((mem[j] != '\n') && (mem[j])) {
934                                 ct->xof += ct->charnr * lineinfo[ct->linenr].x_min;
935 //                              }
936                                 ct++;
937                         }
938                 }
939                 else if ((cu->spacemode == CU_JUSTIFY) && use_textbox) {
940                         float curofs = 0.0f;
941                         for (i = 0; i <= slen; i++) {
942                                 for (j = i;
943                                      (mem[j]) && (mem[j] != '\n') && (chartransdata[j].dobreak == 0) && (j < slen);
944                                      j++)
945                                 {
946                                         /* pass */
947                                 }
948
949                                 if ((mem[j] != '\n') &&
950                                     ((chartransdata[j].dobreak != 0)))
951                                 {
952                                         if (mem[i] == ' ') {
953                                                 struct TempLineInfo *li;
954
955                                                 li = &lineinfo[ct->linenr];
956                                                 curofs += ((li->x_max - li->x_min) + xof_scale) / (float)li->wspace_nr;
957                                         }
958                                         ct->xof += curofs;
959                                 }
960                                 if (mem[i] == '\n' || chartransdata[i].dobreak) curofs = 0;
961                                 ct++;
962                         }
963                 }
964         }
965
966         MEM_freeN(lineinfo);
967
968         /* TEXT ON CURVE */
969         /* Note: Only OB_CURVE objects could have a path  */
970         if (cu->textoncurve && cu->textoncurve->type == OB_CURVE) {
971                 BLI_assert(cu->textoncurve->curve_cache != NULL);
972                 if (cu->textoncurve->curve_cache->path) {
973                         float distfac, imat[4][4], imat3[3][3], cmat[3][3];
974                         float minx, maxx, miny, maxy;
975                         float timeofs, sizefac;
976                         
977                         invert_m4_m4(imat, ob->obmat);
978                         copy_m3_m4(imat3, imat);
979
980                         copy_m3_m4(cmat, cu->textoncurve->obmat);
981                         mul_m3_m3m3(cmat, cmat, imat3);
982                         sizefac = normalize_v3(cmat[0]) / cu->fsize;
983                         
984                         minx = miny = 1.0e20f;
985                         maxx = maxy = -1.0e20f;
986                         ct = chartransdata;
987                         for (i = 0; i <= slen; i++, ct++) {
988                                 if (minx > ct->xof) minx = ct->xof;
989                                 if (maxx < ct->xof) maxx = ct->xof;
990                                 if (miny > ct->yof) miny = ct->yof;
991                                 if (maxy < ct->yof) maxy = ct->yof;
992                         }
993                         
994                         /* we put the x-coordinaat exact at the curve, the y is rotated */
995                         
996                         /* length correction */
997                         distfac = sizefac * cu->textoncurve->curve_cache->path->totdist / (maxx - minx);
998                         timeofs = 0.0f;
999                         
1000                         if (distfac > 1.0f) {
1001                                 /* path longer than text: spacemode involves */
1002                                 distfac = 1.0f / distfac;
1003                                 
1004                                 if (cu->spacemode == CU_RIGHT) {
1005                                         timeofs = 1.0f - distfac;
1006                                 }
1007                                 else if (cu->spacemode == CU_MIDDLE) {
1008                                         timeofs = (1.0f - distfac) / 2.0f;
1009                                 }
1010                                 else if (cu->spacemode == CU_FLUSH) {
1011                                         distfac = 1.0f;
1012                                 }
1013                         }
1014                         else {
1015                                 distfac = 1.0;
1016                         }
1017
1018                         distfac /= (maxx - minx);
1019                         
1020                         timeofs += distfac * cu->xof;  /* not cyclic */
1021                         
1022                         ct = chartransdata;
1023                         for (i = 0; i <= slen; i++, ct++) {
1024                                 float ctime, dtime, vec[4], tvec[4], rotvec[3];
1025                                 float si, co;
1026                                 
1027                                 /* rotate around center character */
1028                                 info = &custrinfo[i];
1029                                 ascii = mem[i];
1030                                 if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
1031                                         ascii = towupper(ascii);
1032                                 }
1033
1034                                 che = find_vfont_char(vfd, ascii);
1035         
1036                                 twidth = char_width(cu, che, info);
1037
1038                                 dtime = distfac * 0.5f * twidth;
1039
1040                                 ctime = timeofs + distfac * (ct->xof - minx);
1041                                 CLAMP(ctime, 0.0f, 1.0f);
1042
1043                                 /* calc the right loc AND the right rot separately */
1044                                 /* vec, tvec need 4 items */
1045                                 where_on_path(cu->textoncurve, ctime, vec, tvec, NULL, NULL, NULL);
1046                                 where_on_path(cu->textoncurve, ctime + dtime, tvec, rotvec, NULL, NULL, NULL);
1047                                 
1048                                 mul_v3_fl(vec, sizefac);
1049                                 
1050                                 ct->rot = (float)M_PI - atan2f(rotvec[1], rotvec[0]);
1051
1052                                 si = sinf(ct->rot);
1053                                 co = cosf(ct->rot);
1054
1055                                 yof = ct->yof;
1056                                 
1057                                 ct->xof = vec[0] + si * yof;
1058                                 ct->yof = vec[1] + co * yof;
1059
1060                                 if (selboxes && (i >= selstart) && (i <= selend)) {
1061                                         EditFontSelBox *sb;
1062                                         sb = &selboxes[i - selstart];
1063                                         sb->rot = -ct->rot;
1064                                 }
1065                                 
1066                         }
1067                 }
1068         }
1069
1070         if (selboxes) {
1071                 ct = chartransdata;
1072                 for (i = 0; i <= selend; i++, ct++) {
1073                         if (i >= selstart) {
1074                                 selboxes[i - selstart].x = ct->xof * cu->fsize;
1075                                 selboxes[i - selstart].y = ct->yof * cu->fsize;
1076                         }
1077                 }
1078         }
1079
1080         if (mode == FO_CURSUP || mode == FO_CURSDOWN || mode == FO_PAGEUP || mode == FO_PAGEDOWN) {
1081                 ct = &chartransdata[ef->pos];
1082
1083                 if ((mode == FO_CURSUP || mode == FO_PAGEUP) && ct->linenr == 0) {
1084                         /* pass */
1085                 }
1086                 else if ((mode == FO_CURSDOWN || mode == FO_PAGEDOWN) && ct->linenr == lnr) {
1087                         /* pass */
1088                 }
1089                 else {
1090                         switch (mode) {
1091                                 case FO_CURSUP:     lnr = ct->linenr - 1; break;
1092                                 case FO_CURSDOWN:   lnr = ct->linenr + 1; break;
1093                                 case FO_PAGEUP:     lnr = ct->linenr - 10; break;
1094                                 case FO_PAGEDOWN:   lnr = ct->linenr + 10; break;
1095                         }
1096                         cnr = ct->charnr;
1097                         /* seek for char with lnr en cnr */
1098                         ef->pos = 0;
1099                         ct = chartransdata;
1100                         for (i = 0; i < slen; i++) {
1101                                 if (ct->linenr == lnr) {
1102                                         if ((ct->charnr == cnr) || ((ct + 1)->charnr == 0)) {
1103                                                 break;
1104                                         }
1105                                 }
1106                                 else if (ct->linenr > lnr) {
1107                                         break;
1108                                 }
1109                                 ef->pos++;
1110                                 ct++;
1111                         }
1112                 }
1113         }
1114         
1115         /* cursor first */
1116         if (ef) {
1117                 float si, co;
1118                 
1119                 ct = &chartransdata[ef->pos];
1120                 si = sinf(ct->rot);
1121                 co = cosf(ct->rot);
1122
1123                 f = ef->textcurs[0];
1124                 
1125                 f[0] = cu->fsize * (-0.1f * co + ct->xof);
1126                 f[1] = cu->fsize * ( 0.1f * si + ct->yof);
1127                 
1128                 f[2] = cu->fsize * ( 0.1f * co + ct->xof);
1129                 f[3] = cu->fsize * (-0.1f * si + ct->yof);
1130                 
1131                 f[4] = cu->fsize * ( 0.1f * co + 0.8f * si + ct->xof);
1132                 f[5] = cu->fsize * (-0.1f * si + 0.8f * co + ct->yof);
1133                 
1134                 f[6] = cu->fsize * (-0.1f * co + 0.8f * si + ct->xof);
1135                 f[7] = cu->fsize * ( 0.1f * si + 0.8f * co + ct->yof);
1136                 
1137         }
1138
1139         if (mode == FO_SELCHANGE) {
1140                 MEM_freeN(chartransdata);
1141                 chartransdata = NULL;
1142                 goto finally;
1143         }
1144
1145         if (mode == FO_EDIT) {
1146                 /* make nurbdata */
1147                 BKE_nurbList_free(r_nubase);
1148                 
1149                 ct = chartransdata;
1150                 for (i = 0; i < slen; i++) {
1151                         unsigned int cha = (unsigned int) mem[i];
1152                         info = &(custrinfo[i]);
1153
1154                         if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
1155                                 cha = towupper(cha);
1156                         }
1157
1158                         if (info->mat_nr > (ob->totcol)) {
1159                                 /* printf("Error: Illegal material index (%d) in text object, setting to 0\n", info->mat_nr); */
1160                                 info->mat_nr = 0;
1161                         }
1162                         /* We do not want to see any character for \n or \r */
1163                         if (cha != '\n')
1164                                 buildchar(bmain, cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i);
1165
1166                         if ((info->flag & CU_CHINFO_UNDERLINE) && (cha != '\n')) {
1167                                 float ulwidth, uloverlap = 0.0f;
1168                                 rctf rect;
1169
1170                                 if ((i < (slen - 1)) && (mem[i + 1] != '\n') &&
1171                                     ((mem[i + 1] != ' ') || (custrinfo[i + 1].flag & CU_CHINFO_UNDERLINE)) &&
1172                                     ((custrinfo[i + 1].flag & CU_CHINFO_WRAP) == 0))
1173                                 {
1174                                         uloverlap = xtrax + 0.1f;
1175                                 }
1176                                 /* Find the character, the characters has to be in the memory already
1177                                  * since character checking has been done earlier already. */
1178                                 che = find_vfont_char(vfd, cha);
1179
1180                                 twidth = char_width(cu, che, info);
1181                                 ulwidth = (twidth * (1.0f + (info->kern / 40.0f))) + uloverlap;
1182
1183                                 rect.xmin = ct->xof;
1184                                 rect.xmax = rect.xmin + ulwidth;
1185
1186                                 rect.ymin = ct->yof;
1187                                 rect.ymax = rect.ymin - cu->ulheight;
1188
1189                                 build_underline(cu, r_nubase,
1190                                                 &rect, cu->ulpos - 0.05f,
1191                                                 ct->rot, i, info->mat_nr);
1192                         }
1193                         ct++;
1194                 }
1195         }
1196
1197         ok = true;
1198
1199 finally:
1200
1201         {
1202                 if (r_text) {
1203                         *r_text = mem;
1204                         *r_text_len = slen;
1205                         *r_text_free = (ef == NULL);
1206                 }
1207                 else {
1208                         if (ef == NULL) {
1209                                 MEM_freeN((void *)mem);
1210                         }
1211                 }
1212         }
1213
1214         if (chartransdata) {
1215                 if (ok && r_chartransdata) {
1216                         *r_chartransdata = chartransdata;
1217                 }
1218                 else {
1219                         MEM_freeN(chartransdata);
1220                 }
1221         }
1222
1223         return ok;
1224
1225 #undef MARGIN_X_MIN
1226 #undef MARGIN_Y_MIN
1227 }
1228
1229
1230 bool BKE_vfont_to_curve_nubase(Main *bmain, Object *ob, int mode, ListBase *r_nubase)
1231 {
1232         BLI_assert(ob->type == OB_FONT);
1233
1234         return BKE_vfont_to_curve_ex(bmain, ob, mode, r_nubase,
1235                                      NULL, NULL, NULL, NULL);
1236 }
1237
1238 bool BKE_vfont_to_curve(Main *bmain, Object *ob, int mode)
1239 {
1240         Curve *cu = ob->data;
1241
1242         return BKE_vfont_to_curve_ex(bmain, ob, mode, &cu->nurb, NULL, NULL, NULL, NULL);
1243 }