forked from iTwin/imodel-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsInterop.cpp
1762 lines (1516 loc) · 74 KB
/
JsInterop.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the repository root for full copyright notice.
*--------------------------------------------------------------------------------------------*/
#if defined (_WIN32) && !defined(BENTLEY_WINRT)
#include <windows.h>
#endif
#include "IModelJsNative.h"
#include <Bentley/Base64Utilities.h>
#include <Bentley/Desktop/FileSystem.h>
#include <GeomSerialization/GeomSerializationApi.h>
#include <ECDb/ChangedIdsIterator.h>
#include <DgnPlatform/FunctionalDomain.h>
#if !defined (BENTLEYCONFIG_NO_VISUALIZATION)
#include <Visualization/Visualization.h>
#endif
#include <DgnPlatform/EntityIdsChangeGroup.h>
#include <chrono>
#include <tuple>
#if defined (BENTLEYCONFIG_PARASOLID)
#include <PSBRepGeometry/PSBRepGeometry.h>
#endif
static Utf8String s_lastECDbIssue;
static BeFileName s_addonDllDir;
static BeFileName s_tempDir;
using namespace ElementDependency;
namespace Render = Dgn::Render;
namespace IModelJsNative {
/*=================================================================================**//**
* An implementation of IKnownLocationsAdmin that is useful for desktop applications.
* This implementation works for Windows, Linux, and MacOS.
* @bsiclass
+===============+===============+===============+===============+===============+======*/
struct KnownLocationsAdmin : PlatformLib::Host::IKnownLocationsAdmin
{
BeFileName m_tempDirectory;
BeFileName m_assetsDirectory;
BeFileNameCR _GetLocalTempDirectoryBaseName() override {return m_tempDirectory;}
BeFileNameCR _GetDgnPlatformAssetsDirectory() override {return m_assetsDirectory;}
//! Construct an instance of the KnownDesktopLocationsAdmin
KnownLocationsAdmin()
{
m_tempDirectory = s_tempDir;
m_assetsDirectory = s_addonDllDir;
m_assetsDirectory.AppendToPath(L"Assets");
}
};
//=======================================================================================
// @bsistruct
//=======================================================================================
struct JsTexture : Texture
{
private:
// We keep a copy of the image data in memory so that it can be embedded into tiles which reference the texture.
// This way the front-end can obtain the image data without making a request to the backend.
ImageSource m_imageSource;
Dimensions m_dimensions;
TextureTransparency m_transparency;
JsTexture(CreateParams const& params, ImageSource::Format format, ByteStream&& data, Dimensions dimensions, TextureTransparency transparency)
: Texture(params), m_imageSource(format, std::move(data)), m_dimensions(dimensions), m_transparency(transparency) { }
static RefCountedPtr<JsTexture> CreateForImage(CreateParams const& params, ImageCR image);
static TextureTransparency DetermineTransparency(ImageCR);
public:
static RefCountedPtr<JsTexture> Create(CreateParams const& params, ImageSourceCR image);
static RefCountedPtr<JsTexture> Create(CreateParams const& params, ImageCR image) { return params.GetKey().IsValid() ? CreateForImage(params, image) : nullptr; }
static RefCountedPtr<JsTexture> Create(GradientSymbCR);
ImageSourceCP GetImageSource() const override { return &m_imageSource; }
Dimensions GetDimensions() const override { return m_dimensions; }
TextureTransparency GetTransparency() const override { return m_transparency; }
};
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
RefCountedPtr<JsTexture> JsTexture::Create(CreateParams const& params, ImageSourceCR src)
{
if (!params.GetKey().IsValid() || !src.IsValid())
return nullptr;
auto size = src.GetSize();
if (size.x <= 0 || size.y <= 0)
return nullptr;
auto transparency = TextureTransparency::Opaque;
if (src.SupportsTransparency())
{
Image image(src, Image::Format::Rgba);
transparency = DetermineTransparency(image);
}
return new JsTexture(params, src.GetFormat(), ByteStream(src.GetByteStream()), Dimensions(size.x, size.y), transparency);
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
RefCountedPtr<JsTexture> JsTexture::Create(GradientSymbCR grad)
{
constexpr size_t size = 0x100;
Image image = grad.GetImage(size, size);
return CreateForImage(Texture::CreateParams(), image);
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
RefCountedPtr<JsTexture> JsTexture::CreateForImage(CreateParams const& params, ImageCR image)
{
if (!image.IsValid())
return nullptr;
auto format = Image::Format::Rgba == image.GetFormat() ? ImageSource::Format::Png : ImageSource::Format::Jpeg;
ImageSource src(image, format);
if (!src.IsValid())
return nullptr;
return new JsTexture(params, format, std::move(src.GetByteStreamR()), Dimensions(image.GetWidth(), image.GetHeight()), DetermineTransparency(image));
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
TextureTransparency JsTexture::DetermineTransparency(ImageCR image)
{
if (!image.IsValid() || Image::Format::Rgba != image.GetFormat())
return TextureTransparency::Opaque;
bool haveOpaque = false;
bool haveTranslucent = false;
uint8_t maxAlpha = 240; // See DisplayParams::GetMinTransparency()
ByteStreamCR bytes = image.GetByteStream();
uint8_t const* data = bytes.GetData();
for (size_t i = 0; i < bytes.size(); i += 4)
{
uint8_t a = data[i + 3];
if (a > maxAlpha)
{
haveOpaque = true;
if (haveTranslucent)
return TextureTransparency::Mixed;
}
else
{
haveTranslucent = true;
if (haveOpaque)
return TextureTransparency::Mixed;
}
}
BeAssert(!haveOpaque || !haveTranslucent);
return haveTranslucent ? TextureTransparency::Translucent : TextureTransparency::Opaque;
}
//=======================================================================================
// @bsistruct
//=======================================================================================
struct JsMaterial : Material
{
private:
explicit JsMaterial(CreateParams const& params) : Material(params) { }
public:
static RefCountedPtr<JsMaterial> Create(CreateParams const& params)
{
return params.m_key.IsValid() ? new JsMaterial(params) : nullptr;
}
};
DEFINE_REF_COUNTED_PTR(JsTexture);
DEFINE_REF_COUNTED_PTR(JsMaterial);
//=======================================================================================
// This caches textures per-DgnDb so that we do not have to recreate them constantly or
// hold duplicates of the same texture in memory. We preserve the image data so that it
// can be embedded into tile bytes to be deserialized on front-end.
// @bsistruct
//=======================================================================================
struct ResourceCache : DgnDb::AppData
{
private:
template<typename K, typename V> struct ResourceMap
{
private:
typedef RefCountedPtr<V> VPtr;
bmap<K, VPtr> m_resources;
public:
V* Find(K const& key)
{
auto it = m_resources.find(key);
return m_resources.end() == it ? nullptr : it->second.get();
}
void Insert(K const& key, V* value) { m_resources.Insert(key, value); }
void Clear() { m_resources.clear(); }
size_t size() const { return m_resources.size(); }
};
static Key const& GetKey() { static Key s_key; return s_key; }
BeMutex m_mutex;
ResourceMap<TextureKey, JsTexture> m_textures;
ResourceMap<GradientSymb, JsTexture> m_gradients;
ResourceMap<MaterialKey, JsMaterial> m_materials;
void Add(TextureKey key, JsTexture* texture);
void Add(GradientSymbCR grad, JsTexture* texture) { m_gradients.Insert(grad, texture); }
void Add(MaterialKey key, JsMaterial* material) { BeAssert(key.IsValid()); m_materials.Insert(key, material); }
JsTexturePtr CreateTexture(ImageCR, Texture::CreateParams const&);
JsTexturePtr CreateTexture(ImageSourceCR, Texture::CreateParams const&);
template<typename F> auto UnderMutex(F func) -> decltype(func())
{
BeMutexHolder lock(m_mutex);
return func();
}
public:
JsTexturePtr FindTexture(TextureKey key) { return key.IsValid() ? UnderMutex([&]() { return m_textures.Find(key); }) : nullptr; }
JsMaterial* FindMaterial(MaterialKey key) { return key.IsValid() ? UnderMutex([&]() { return m_materials.Find(key); }) : nullptr; }
JsTexturePtr GetGradient(GradientSymbCR);
JsTexturePtr GetTexture(ImageSourceCR, Texture::CreateParams const&, Image::BottomUp = Image::BottomUp::No);
JsTexturePtr GetTexture(ImageCR, Texture::CreateParams const&);
JsMaterialPtr GetMaterial(Material::CreateParams const& params);
static ResourceCache& Get(DgnDbR db) { return *db.ObtainAppData(GetKey(), []() { return new ResourceCache(); }); }
~ResourceCache() { m_textures.Clear(); m_gradients.Clear(); m_materials.Clear(); }
};
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
void ResourceCache::Add(TextureKey key, JsTexture* texture)
{
// We only cache persistent textures. We cache even if null, so we don't waste time repeatedly trying and failing to create the same texture.
BeAssert(key.IsValid());
if (key.IsPersistent())
m_textures.Insert(key, texture);
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
JsMaterialPtr ResourceCache::GetMaterial(Material::CreateParams const& params)
{
BeMutexHolder lock(m_mutex);
RefCountedPtr<JsMaterial> mat = FindMaterial(params.m_key);
if (mat.IsNull())
{
mat = JsMaterial::Create(params);
if (params.m_key.IsPersistent())
Add(params.m_key, mat.get());
}
return mat;
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
JsTexturePtr ResourceCache::GetGradient(GradientSymbCR grad)
{
BeMutexHolder lock(m_mutex);
RefCountedPtr<JsTexture> tex = m_gradients.Find(grad);
if (tex.IsNull())
{
tex = JsTexture::Create(grad);
Add(grad, tex.get());
}
return tex;
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
JsTexturePtr ResourceCache::GetTexture(ImageSourceCR src, Texture::CreateParams const& params, Image::BottomUp)
{
if (!params.GetKey().IsValid())
return nullptr;
BeMutexHolder lock(m_mutex);
auto tex = FindTexture(params.GetKey());
if (tex.IsNull())
tex = CreateTexture(src, params);
return tex;
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
JsTexturePtr ResourceCache::GetTexture(ImageCR img, Texture::CreateParams const& params)
{
if (!params.GetKey().IsValid())
return nullptr;
BeMutexHolder lock(m_mutex);
auto tex = FindTexture(params.GetKey());
if (tex.IsNull())
tex = CreateTexture(img, params);
return tex;
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
JsTexturePtr ResourceCache::CreateTexture(ImageSourceCR src, Texture::CreateParams const& params)
{
BeAssert(params.GetKey().IsValid());
BeAssert(FindTexture(params.GetKey()).IsNull());
auto tex = JsTexture::Create(params, src);
Add(params.GetKey(), tex.get());
return tex;
}
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
JsTexturePtr ResourceCache::CreateTexture(ImageCR img, Texture::CreateParams const& params)
{
BeAssert(params.GetKey().IsValid());
BeAssert(FindTexture(params.GetKey()).IsNull());
auto tex = JsTexture::Create(params, img);
Add(params.GetKey(), tex.get());
return tex;
}
#define NO_IMPL(ret) { BeAssert(false); return ret; }
#define NULL_IMPL NO_IMPL(nullptr)
#define RETURN_GRAPHIC { return new Render::Graphic(db); }
//=======================================================================================
// @bsistruct
//=======================================================================================
struct JsRenderSystem : Render::System
{
Render::MaterialPtr _FindMaterial(Render::MaterialKeyCR key, Dgn::DgnDbR db) const override { return ResourceCache::Get(db).FindMaterial(key); }
Render::MaterialPtr _CreateMaterial(Render::Material::CreateParams const& params, Dgn::DgnDbR db) const override { return ResourceCache::Get(db).GetMaterial(params); }
Render::TexturePtr _FindTexture(Render::TextureKeyCR key, Dgn::DgnDbR db) const override { return ResourceCache::Get(db).FindTexture(key); }
Render::TexturePtr _CreateTexture(Render::ImageCR img, Dgn::DgnDbR db, Render::Texture::CreateParams const& params) const override
{
return ResourceCache::Get(db).GetTexture(img, params);
}
Render::TexturePtr _CreateTexture(Render::ImageSourceCR src, Render::Image::BottomUp, Dgn::DgnDbR db, Render::Texture::CreateParams const& params) const override
{
return ResourceCache::Get(db).GetTexture(src, params);
}
Render::TexturePtr _GetTexture(Render::GradientSymbCR grad, Dgn::DgnDbR db) const override
{
return ResourceCache::Get(db).GetGradient(grad);
}
};
//=======================================================================================
// @bsistruct
//=======================================================================================
struct JsDgnHost : PlatformLib::Host {
private:
BeMutex m_mutex;
JsRenderSystem m_renderSystem;
IKnownLocationsAdmin& _SupplyIKnownLocationsAdmin() override { return *new KnownLocationsAdmin(); }
#if !defined (BENTLEYCONFIG_NO_VISUALIZATION)
VisualizationAdmin& _SupplyVisualizationAdmin() override {
auto viz = VisualizationUPtr(iTwinVisualization_create(&m_renderSystem));
return *new VisualizationAdmin(std::move(viz));
}
#endif
#if defined (BENTLEYCONFIG_PARASOLID)
BRepGeometryAdmin& _SupplyBRepGeometryAdmin() override {return *new BentleyApi::Psolid::PSolidKernelAdmin();}
#endif
public:
JsDgnHost() { BeAssertFunctions::SetBeAssertHandler(&JsInterop::HandleAssertion);}
};
} // namespace IModelJsNative
using namespace IModelJsNative;
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::Initialize(BeFileNameCR addonDllDir, Napi::Env env, BeFileNameCR tempDir) {
Env() = env;
MainThreadId() = BeThreadUtilities::GetCurrentThreadId();
s_addonDllDir = addonDllDir;
s_tempDir = tempDir;
#if defined(BENTLEYCONFIG_OS_WINDOWS_DESKTOP) // excludes WinRT
// Include this location for delay load of pskernel...
WString newPath;
newPath = L"PATH=" + addonDllDir + L";";
PUSH_DISABLE_DEPRECATION_WARNINGS
newPath.append(::_wgetenv(L"PATH"));
POP_DISABLE_DEPRECATION_WARNINGS
_wputenv(newPath.c_str());
// Defeat node's attempt to turn off WER
auto errMode = GetErrorMode();
errMode &= ~SEM_NOGPFAULTERRORBOX;
SetErrorMode(errMode);
#endif
static std::once_flag s_initFlag;
std::call_once(s_initFlag, []() {
auto jsHost = new JsDgnHost();
PlatformLib::Initialize(*jsHost);
RegisterOptionalDomains();
InitLogging();
InitializeSolidKernel();
BeFileName path = PlatformLib::GetHost().GetIKnownLocationsAdmin().GetDgnPlatformAssetsDirectory();
path.AppendToPath(L"RscFonts.itwin-workspace");
FontManager::AddWorkspaceDb(path.GetNameUtf8().c_str(), nullptr);
});
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::RegisterOptionalDomains()
{
DgnDomains::RegisterDomain(FunctionalDomain::GetDomain(), DgnDomain::Required::No, DgnDomain::Readonly::No);
}
static RefCountedPtr<IRefCounted> s_solidKernelMainThreadMark;
/*---------------------------------------------------------------------------------**//**
* @bsimethod
+---------------+---------------+---------------+---------------+---------------+------*/
void JsInterop::InitializeSolidKernel()
{
T_HOST.GetBRepGeometryAdmin()._StartSession();
if (s_solidKernelMainThreadMark.IsNull())
s_solidKernelMainThreadMark = T_HOST.GetBRepGeometryAdmin()._CreateMainThreadMark();
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
NativeLogging::CategoryLogger JsInterop::GetNativeLogger() {
return NativeLogging::CategoryLogger("imodeljs");
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
Napi::Object JsInterop::ConcurrentQueryResetConfig(Napi::Env env, ECDbCR ecdb) {
auto outConf = Napi::Object::New(env);
ConcurrentQueryMgr::ResetConfig(ecdb).To(outConf);
return outConf;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
Napi::Object JsInterop::ConcurrentQueryResetConfig(Napi::Env env, ECDbCR ecdb, Napi::Object configObj) {
if (configObj.IsObject()) {
auto outConf = Napi::Object::New(env);
BeJsValue inJsConf(configObj);
auto inConf = ConcurrentQueryMgr::Config::From(inJsConf);
ConcurrentQueryMgr::ResetConfig(ecdb, inConf).To(outConf);
return outConf;
}
return ConcurrentQueryResetConfig(env, ecdb);
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::ConcurrentQueryExecute(ECDbCR ecdb, Napi::Object requestObj, Napi::Function callback) {
auto& mgr = ConcurrentQueryMgr::GetInstance(ecdb);
BeJsValue beJsReq(requestObj);
auto request = QueryRequest::Deserialize(beJsReq);
if (request->UsePrimaryConnection()) {
mgr.Enqueue(std::move(request), [&](QueryResponse::Ptr value) {
auto jsResp = Napi::Object::New(Env());
auto beJsResp = BeJsValue(jsResp);
if (value->GetKind() == QueryResponse::Kind::NoResult) {
value->ToJs(beJsResp, false);
}
else if (value->GetKind() == QueryResponse::Kind::ECSql) {
auto& resp = value->GetAsConst<ECSqlResponse>();
resp.ToJs(beJsResp, false);
if (!resp.asJsonString().empty()) {
auto parse = Env().Global().Get("JSON").As<Napi::Object>().Get("parse").As<Napi::Function>();
auto rows = Napi::String::New(Env(), resp.asJsonString());
jsResp[ECSqlResponse::JData] = parse({ rows });
}
}
else if (value->GetKind() == QueryResponse::Kind::BlobIO) {
auto& resp = value->GetAsConst<BlobIOResponse>();
if (resp.GetLength() > 0) {
resp.ToJs(beJsResp, false);
auto blob = Napi::Uint8Array::New(Env(), resp.GetLength());
memcpy(blob.Data(), resp.GetData(), resp.GetLength());
jsResp[BlobIOResponse::JData] = blob;
}
}
else {
BeNapi::ThrowJsException(Env(), "concurrent query: unsupported response type");
}
callback.Call({ jsResp });
});
return;
}
auto threadSafeFunc = Napi::ThreadSafeFunction::New(requestObj.Env(), callback, "concurrent_query", 0, 1);
mgr.Enqueue(std::move(request), [=](QueryResponse::Ptr value) {
if(threadSafeFunc.BlockingCall (
[=]( Napi::Env env, Napi::Function jsCallback) {
auto jsResp = Napi::Object::New(env);
auto beJsResp = BeJsValue(jsResp);
if (value->GetKind() == QueryResponse::Kind::NoResult) {
value->ToJs(beJsResp, false);
} else if (value->GetKind() == QueryResponse::Kind::ECSql) {
auto& resp = value->GetAsConst<ECSqlResponse>();
resp.ToJs(beJsResp, false);
if (!resp.asJsonString().empty()) {
auto parse = env.Global().Get("JSON").As<Napi::Object>().Get("parse").As<Napi::Function>();
auto rows = Napi::String::New(env, resp.asJsonString());
jsResp[ECSqlResponse::JData] = parse({rows});
}
} else if (value->GetKind() == QueryResponse::Kind::BlobIO) {
auto& resp = value->GetAsConst<BlobIOResponse>();
if (resp.GetLength() > 0) {
resp.ToJs(beJsResp, false);
auto blob = Napi::Uint8Array::New(env, resp.GetLength());
memcpy(blob.Data(), resp.GetData(), resp.GetLength());
jsResp[BlobIOResponse::JData] = blob;
}
} else {
BeNapi::ThrowJsException(env, "concurrent query: unsupported response type");
}
jsCallback.Call({jsResp});
}) != napi_ok) {
// do nothing
}
const_cast<Napi::ThreadSafeFunction&>(threadSafeFunc).Release();
});
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
DgnDbPtr JsInterop::CreateIModel(Utf8StringCR filenameIn, BeJsConst props) {
auto rootSubject = props[json_rootSubject()];
if (!rootSubject.isStringMember(json_name()))
BeNapi::ThrowJsException(Env(), "Root subject name is missing");
BeFileName filename(filenameIn);
BeFileName path = filename.GetDirectoryName();
if (!path.DoesPathExist()) {
Utf8String err = Utf8String("Path [") + path.GetNameUtf8() + "] does not exist";
BeNapi::ThrowJsException(Env(), err.c_str());
}
CreateDgnDbParams params(rootSubject[json_name()].asCString());
if (rootSubject.isStringMember(json_description()))
params.SetRootSubjectDescription(rootSubject[json_description()].asCString());
if (props.isMember(json_globalOrigin()))
params.m_globalOrigin = BeJsGeomUtils::ToDPoint3d(props[json_globalOrigin()]);
if (props.isStringMember(json_guid()))
params.m_guid.FromString(props[json_guid()].asCString());
if (props.isMember(json_projectExtents()))
params.m_projectExtents.FromJson(props[json_projectExtents()]);
if (props.isStringMember(json_client()))
params.m_client = props[json_client()].asCString();
RefCountedPtr<BusyRetry> retryHandler;
if (!params.IsReadonly())
params.SetBusyRetry(new BeSQLite::BusyRetry(40, 500)); // retry 40 times, 1/2 second intervals (20 seconds total)
DbResult result;
DgnDbPtr db = DgnDb::CreateIModel(&result, filename, params);
if (!db.IsValid())
throwSqlResult("cannot create iModel", filenameIn.c_str(), result);
return db;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
ChangesetStatus JsInterop::DumpChangeSet(DgnDbR dgndb, BeJsConst changeSet)
{
ChangesetPropsPtr revision = GetChangesetProps(dgndb.GetDbGuid().ToString(), changeSet);
revision->Dump(dgndb);
return ChangesetStatus::Success;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
DgnDbStatus JsInterop::ExtractChangedInstanceIdsFromChangeSets(BeJsValue jsonOut, DgnDbR db, const bvector<BeFileName>& changeSetFiles)
{
Json::Value elementJson(Json::ValueType::objectValue);
Json::Value elementInsertIds(Json::ValueType::arrayValue);
Json::Value elementUpdateIds(Json::ValueType::arrayValue);
Json::Value elementDeleteIds(Json::ValueType::arrayValue);
Json::Value aspectJson(Json::ValueType::objectValue);
Json::Value aspectInsertIds(Json::ValueType::arrayValue);
Json::Value aspectUpdateIds(Json::ValueType::arrayValue);
Json::Value aspectDeleteIds(Json::ValueType::arrayValue);
Json::Value modelJson(Json::ValueType::objectValue);
Json::Value modelInsertIds(Json::ValueType::arrayValue);
Json::Value modelUpdateIds(Json::ValueType::arrayValue);
Json::Value modelDeleteIds(Json::ValueType::arrayValue);
Json::Value relationshipJson(Json::ValueType::objectValue);
Json::Value relationshipInsertIds(Json::ValueType::arrayValue);
Json::Value relationshipUpdateIds(Json::ValueType::arrayValue);
Json::Value relationshipDeleteIds(Json::ValueType::arrayValue);
Json::Value codeSpecJson(Json::ValueType::objectValue);
Json::Value codeSpecInsertIds(Json::ValueType::arrayValue);
Json::Value codeSpecUpdateIds(Json::ValueType::arrayValue);
Json::Value codeSpecDeleteIds(Json::ValueType::arrayValue);
Json::Value fontJson(Json::ValueType::objectValue);
Json::Value fontInsertIds(Json::ValueType::arrayValue);
Json::Value fontUpdateIds(Json::ValueType::arrayValue);
Json::Value fontDeleteIds(Json::ValueType::arrayValue);
EntityIdsChangeGroup entityIdsChangeGroup;
entityIdsChangeGroup.ExtractChangedInstanceIdsFromChangeSets(db, changeSetFiles);
for (auto& opsAndJsonIds : {
std::tie(entityIdsChangeGroup.elementOps, elementInsertIds, elementUpdateIds, elementDeleteIds),
std::tie(entityIdsChangeGroup.aspectOps, aspectInsertIds, aspectUpdateIds, aspectDeleteIds),
std::tie(entityIdsChangeGroup.modelOps, modelInsertIds, modelUpdateIds, modelDeleteIds),
std::tie(entityIdsChangeGroup.relationshipOps, relationshipInsertIds, relationshipUpdateIds, relationshipDeleteIds),
std::tie(entityIdsChangeGroup.codeSpecOps, codeSpecInsertIds, codeSpecUpdateIds, codeSpecDeleteIds),
std::tie(entityIdsChangeGroup.fontOps, fontInsertIds, fontUpdateIds, fontDeleteIds)
})
{
// can replace this all in C++17 with a destructuring assignment in the loop decl
const auto& opMap = std::get<0>(opsAndJsonIds);
auto& insertIds = std::get<1>(opsAndJsonIds);
auto& updateIds = std::get<2>(opsAndJsonIds);
auto& deleteIds = std::get<3>(opsAndJsonIds);
for (const auto& entry : opMap)
{
const auto& id = entry.first;
const auto& op = entry.second;
if (op == DbOpcode::Insert) insertIds.append(id.ToHexStr());
if (op == DbOpcode::Update) updateIds.append(id.ToHexStr());
if (op == DbOpcode::Delete) deleteIds.append(id.ToHexStr());
}
}
if (elementInsertIds.size() > 0) elementJson["insert"] = elementInsertIds;
if (elementUpdateIds.size() > 0) elementJson["update"] = elementUpdateIds;
if (elementDeleteIds.size() > 0) elementJson["delete"] = elementDeleteIds;
if (!elementJson.empty()) jsonOut["element"].From(elementJson);
if (aspectInsertIds.size() > 0) aspectJson["insert"] = aspectInsertIds;
if (aspectUpdateIds.size() > 0) aspectJson["update"] = aspectUpdateIds;
if (aspectDeleteIds.size() > 0) aspectJson["delete"] = aspectDeleteIds;
if (!aspectJson.empty()) jsonOut["aspect"].From(aspectJson);
if (modelInsertIds.size() > 0) modelJson["insert"] = modelInsertIds;
if (modelUpdateIds.size() > 0) modelJson["update"] = modelUpdateIds;
if (modelDeleteIds.size() > 0) modelJson["delete"] = modelDeleteIds;
if (!modelJson.empty()) jsonOut["model"].From(modelJson);
if (relationshipInsertIds.size() > 0) relationshipJson["insert"] = relationshipInsertIds;
if (relationshipUpdateIds.size() > 0) relationshipJson["update"] = relationshipUpdateIds;
if (relationshipDeleteIds.size() > 0) relationshipJson["delete"] = relationshipDeleteIds;
if (!relationshipJson.empty()) jsonOut["relationship"].From(relationshipJson);
if (codeSpecInsertIds.size() > 0) codeSpecJson["insert"] = codeSpecInsertIds;
if (codeSpecUpdateIds.size() > 0) codeSpecJson["update"] = codeSpecUpdateIds;
if (codeSpecDeleteIds.size() > 0) codeSpecJson["delete"] = codeSpecDeleteIds;
if (!codeSpecJson.empty()) jsonOut["codeSpec"].From(codeSpecJson);
if (fontInsertIds.size() > 0) fontJson["insert"] = fontInsertIds;
if (fontUpdateIds.size() > 0) fontJson["update"] = fontUpdateIds;
if (fontDeleteIds.size() > 0) fontJson["delete"] = fontDeleteIds;
if (!fontJson.empty()) jsonOut["font"].From(fontJson);
return DgnDbStatus::Success;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
ChangesetPropsPtr JsInterop::GetChangesetProps(Utf8StringCR dbGuid, BeJsConst arg) {
if (!arg.isStringMember("id") || !arg.isNumericMember("index") || !arg.isStringMember("pathname") || !arg.isStringMember("parentId"))
ThrowJsException("id, index, pathname, and parentId must all be members of ChangesetProps");
BeFileName changeSetPathname(arg["pathname"].asString().c_str(), true);
if (!changeSetPathname.DoesPathExist())
ThrowJsException("changeset file not found");
ChangesetPropsPtr changeset = new ChangesetProps(arg["id"].asString(), arg["index"].asInt(), arg["parentId"].asString(), dbGuid, changeSetPathname, (ChangesetProps::ChangesetType)arg["changesType"].asInt());
if (arg.isStringMember("pushDate"))
changeset->SetDateTime(DateTime::FromString(arg["pushDate"].asString().c_str()));
return changeset;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
bvector<ChangesetPropsPtr> JsInterop::GetChangesetPropsVec(bool& containsSchemaChanges, Utf8StringCR dbGuid, BeJsConst changeSets) {
containsSchemaChanges = false;
if (!changeSets.isArray())
ThrowJsException("changesets must be an array");
bvector<ChangesetPropsPtr> changesetVec;
for (uint32_t i = 0; i < changeSets.size(); ++i) {
BeJsConst changeSet = changeSets[i];
changesetVec.push_back(GetChangesetProps(dbGuid, changeSet));
if (!containsSchemaChanges)
containsSchemaChanges = changeSet["isSchemaChange"].GetBoolean();
}
return changesetVec;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
ChangesetStatus JsInterop::ApplySchemaChangeSet(BeFileNameCR dbFileName, bvector<ChangesetPropsCP> const& revisions, RevisionProcessOption applyOption)
{
SchemaUpgradeOptions schemaUpgradeOptions(revisions, applyOption);
schemaUpgradeOptions.SetUpgradeFromDomains(SchemaUpgradeOptions::DomainUpgradeOptions::SkipCheck);
DgnDb::OpenParams openParams(Db::OpenMode::ReadWrite, BeSQLite::DefaultTxn::Yes, schemaUpgradeOptions);
DbResult result;
DgnDbPtr dgndb = DgnDb::OpenIModelDb(&result, dbFileName, openParams);
POSTCONDITION(result == BE_SQLITE_OK, ChangesetStatus::ApplyError);
result = dgndb->SaveChanges();
POSTCONDITION(result == BE_SQLITE_OK, ChangesetStatus::ApplyError);
dgndb->CloseDb();
return ChangesetStatus::Success;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::GetRowAsJson(BeJsValue rowJson, ECSqlStatement& stmt)
{
JsonECSqlSelectAdapter adapter(stmt, JsonECSqlSelectAdapter::FormatOptions(JsonECSqlSelectAdapter::MemberNameCasing::LowerFirstChar, ECJsonInt64Format::AsHexadecimalString));
adapter.GetRow(rowJson, true);
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::GetECValuesCollectionAsJson(BeJsValue json, ECN::ECValuesCollectionCR props)
{
for (ECN::ECPropertyValue const& prop : props)
{
if (prop.HasChildValues())
GetECValuesCollectionAsJson(json[prop.GetValueAccessor().GetAccessString(prop.GetValueAccessor().GetDepth()-1)], *prop.GetChildValues());
else
{
ECN::PrimitiveECPropertyCP propertyPtr = prop.GetValueAccessor().GetECProperty()->GetAsPrimitiveProperty();
ECN::IECInstanceCR instance = prop.GetInstance();
if(propertyPtr != nullptr)
JsonEcInstanceWriter::WritePrimitiveValue(json, *propertyPtr, instance, nullptr);
}
}
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
DbResult JsInterop::OpenECDb(ECDbR ecdb, BeFileNameCR pathname, BeSQLite::Db::OpenParams const& params)
{
if (!pathname.DoesPathExist())
return BE_SQLITE_NOTFOUND;
DbResult res = ecdb.OpenBeSQLiteDb(pathname, params);
if (res != BE_SQLITE_OK)
return res;
return BE_SQLITE_OK;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
DbResult JsInterop::CreateECDb(ECDbR ecdb, BeFileNameCR pathname)
{
BeFileName path = pathname.GetDirectoryName();
if (!path.DoesPathExist())
return BE_SQLITE_NOTFOUND;
DbResult res = ecdb.CreateNewDb(pathname);
if (res != BE_SQLITE_OK)
return res;
return BE_SQLITE_OK;
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
DbResult JsInterop::ImportSchema(ECDbR ecdb, BeFileNameCR pathname)
{
if (!pathname.DoesPathExist())
return BE_SQLITE_NOTFOUND;
ECSchemaReadContextPtr schemaContext = ECSchemaReadContext::CreateContext(false /*=acceptLegacyImperfectLatestCompatibleMatch*/, true /*=includeFilesWithNoVerExt*/);
JsInterop::AddFallbackSchemaLocaters(ecdb, schemaContext);
ECSchemaPtr schema;
SchemaReadStatus schemaStatus = ECSchema::ReadFromXmlFile(schema, pathname.GetName(), *schemaContext);
if (SchemaReadStatus::Success != schemaStatus)
return BE_SQLITE_ERROR;
bvector<ECSchemaCP> schemas;
schemas.push_back(schema.get());
BentleyStatus status = ecdb.Schemas().ImportSchemas(schemas);
if (status != SUCCESS)
return BE_SQLITE_ERROR;
return ecdb.SaveChanges();
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::AddFallbackSchemaLocaters(ECDbR db, ECSchemaReadContextPtr schemaContext)
{
// Add the db then the standard schema paths as fallback locations to load referenced schemas.
schemaContext->SetFinalSchemaLocater(db.GetSchemaLocater());
AddFallbackSchemaLocaters(schemaContext);
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
void JsInterop::AddFallbackSchemaLocaters(ECSchemaReadContextPtr schemaContext)
{
// Add the standard schema paths as fallback locations to load referenced schemas.
BeFileName rootDir = PlatformLib::GetHost().GetIKnownLocationsAdmin().GetDgnPlatformAssetsDirectory();
rootDir.AppendToPath(L"ECSchemas");
BeFileName dgnPath = rootDir;
dgnPath.AppendToPath(L"Dgn").AppendSeparator();
BeFileName domainPath = rootDir;
domainPath.AppendToPath(L"Domain").AppendSeparator();
BeFileName ecdbPath = rootDir;
ecdbPath.AppendToPath(L"ECDb").AppendSeparator();
bvector<WString> searchPaths;
searchPaths.push_back(dgnPath);
searchPaths.push_back(domainPath);
searchPaths.push_back(ecdbPath);
schemaContext->AddFinalSchemaPaths(searchPaths);
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
DbResult JsInterop::ImportSchemas(DgnDbR dgndb, bvector<Utf8String> const& schemaSources, SchemaSourceType sourceType, const SchemaImportOptions& opts)
{
if (0 == schemaSources.size())
return BE_SQLITE_ERROR;
ECSchemaReadContextPtr schemaContext = opts.m_customSchemaContext;
if (schemaContext.IsNull())
schemaContext = ECSchemaReadContext::CreateContext(false /*=acceptLegacyImperfectLatestCompatibleMatch*/, true /*=includeFilesWithNoVerExt*/);
JsInterop::AddFallbackSchemaLocaters(dgndb, schemaContext);
bvector<ECSchemaCP> schemas;
for (Utf8String schemaSource : schemaSources)
{
ECSchemaPtr schema;
SchemaReadStatus schemaStatus;
if (sourceType == SchemaSourceType::File)
{
BeFileName schemaFile(schemaSource.c_str(), BentleyCharEncoding::Utf8);
if (!schemaFile.DoesPathExist())
return BE_SQLITE_ERROR_FileNotFound;
schema = ECSchema::LocateSchema(schemaSource.c_str(), *schemaContext, SchemaMatchType::Exact, &schemaStatus);
}
else
schemaStatus = ECSchema::ReadFromXmlString(schema, schemaSource.c_str(), *schemaContext);
if (SchemaReadStatus::DuplicateSchema == schemaStatus)
continue;
if (SchemaReadStatus::Success != schemaStatus)
return BE_SQLITE_ERROR;
schemas.push_back(schema.get());
}
if (0 == schemas.size())
return BE_SQLITE_ERROR;
SchemaStatus status = dgndb.ImportSchemas(schemas, opts.m_schemaLockHeld, DgnDb::SyncDbUri(opts.m_schemaSyncDbUri.c_str())); // NOTE: this calls DgnDb::ImportSchemas which has additional processing over SchemaManager::ImportSchemas
if (status != SchemaStatus::Success)
return DgnDb::SchemaStatusToDbResult(status, true);
return dgndb.SaveChanges();
}
//---------------------------------------------------------------------------------------
// @bsimethod
//---------------------------------------------------------------------------------------
Napi::Value JsInterop::GetInstance(ECDbR db, NapiInfoCR info) {
constexpr auto kUseJsName = "useJsNames";
constexpr auto kClassId = "classId";
constexpr auto kClassIdsToClassNames = "classIdsToClassNames";
constexpr auto kAbbreviateBlobs = "abbreviateBlobs";
constexpr auto kId = "id";
constexpr auto kSerializationMethod = "serializationMethod";
enum SerializationMethod {
JsonParse = 0,
BeJsNapi = 1
};
REQUIRE_ARGUMENT_ANY_OBJ(0, argsObj);
ECInstanceId instanceId;
ECClassId classId;
SerializationMethod serializationMethod = SerializationMethod::JsonParse;
auto abbreviateBlobs = true;
auto classIdsToClassNames = false;
auto useJsNames = false;
auto jsId = argsObj.Get(kId);
if (!jsId.IsString()) {
THROW_JS_EXCEPTION("'id' property is not optional and must be of type Id64String");
} else {
ECInstanceId::FromString(instanceId, jsId.ToString().Utf8Value().c_str());
}
auto jsClassId = argsObj.Get(kClassId);
if (!jsClassId.IsString()) {
THROW_JS_EXCEPTION("'classId' property is not optional and must be of type Id64String");
} else{
ECClassId::FromString(classId, jsClassId.ToString().Utf8Value().c_str());
}
auto jsSerializationMethod = argsObj.Get(kSerializationMethod);
if (jsSerializationMethod.IsNumber()) {
int method = jsSerializationMethod.ToNumber().Int32Value();
if (method == SerializationMethod::JsonParse || method == SerializationMethod::BeJsNapi) {
serializationMethod = static_cast<SerializationMethod>(method);
} else {
THROW_JS_EXCEPTION("'serializationMethod' property must be either 0 or 1");
}
}
auto jsAbbreviateBlobs = argsObj.Get(kAbbreviateBlobs);
if (jsAbbreviateBlobs.IsBoolean()) {
abbreviateBlobs = jsAbbreviateBlobs.ToBoolean().Value();
}
auto jsClassIdsToClassNames = argsObj.Get(kClassIdsToClassNames);
if (jsClassIdsToClassNames.IsBoolean()) {
classIdsToClassNames = jsClassIdsToClassNames.ToBoolean().Value();
}
auto jsUseJsNames = argsObj.Get(kUseJsName);
if (jsUseJsNames.IsBoolean()) {
useJsNames = jsUseJsNames.ToBoolean().Value();
}
if (!instanceId.IsValid()){
THROW_JS_EXCEPTION("Invalid instanceId");
}
if (!classId.IsValid()) {
THROW_JS_EXCEPTION("Invalid classId");
}
auto& instanceReader = db.GetInstanceReader();
InstanceReader::Options options;
options.SetForceSeek(true);
auto position = InstanceReader::Position{instanceId, classId, nullptr};
if (serializationMethod == SerializationMethod::JsonParse) {
Napi::Value val;
if (!instanceReader.Seek(position,
[&](InstanceReader::IRowContext const& row) {
InstanceReader::JsonParams params;