App_Main.py 446 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from AppObjects.ObjectCollection import *
  50. from AppObjects.FlatCAMObj import FlatCAMObj
  51. from AppObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from AppParsers.ParseExcellon import Excellon
  54. from AppParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM AppGUI
  57. from AppGUI.PlotCanvas import *
  58. from AppGUI.PlotCanvasLegacy import *
  59. from AppGUI.MainGUI import *
  60. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from AppPreProcessor import load_preprocessors
  63. # FlatCAM AppEditors
  64. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from AppEditors.FlatCAMTextEditor import TextEditor
  68. from AppParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from AppProcess import *
  71. from AppWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from AppTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import AppTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = 8.993
  136. version_date = "2020/08/01"
  137. beta = True
  138. engine = '3D'
  139. # current date now
  140. date = str(datetime.today()).rpartition('.')[0]
  141. date = ''.join(c for c in date if c not in ':-')
  142. date = date.replace(' ', '_')
  143. # ###############################################################################################################
  144. # ############################################ URLS's ###########################################################
  145. # ###############################################################################################################
  146. # URL for update checks and statistics
  147. version_url = "http://flatcam.org/version"
  148. # App URL
  149. app_url = "http://flatcam.org"
  150. # Manual URL
  151. manual_url = "http://flatcam.org/manual/index.html"
  152. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  153. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  154. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  155. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  156. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  157. # this variable will hold the project status
  158. # if True it will mean that the project was modified and not saved
  159. should_we_save = False
  160. # flag is True if saving action has been triggered
  161. save_in_progress = False
  162. # ###############################################################################################################
  163. # ####################################### APP Signals ######################################################
  164. # ###############################################################################################################
  165. # Inform the user
  166. # Handled by:
  167. # * App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal([str], [str, bool])
  169. app_quit = QtCore.pyqtSignal()
  170. # General purpose background task
  171. worker_task = QtCore.pyqtSignal(dict)
  172. # File opened
  173. # Handled by:
  174. # * register_folder()
  175. # * register_recent()
  176. # Note: Setting the parameters to unicode does not seem
  177. # to have an effect. Then are received as Qstring
  178. # anyway.
  179. # File type and filename
  180. file_opened = QtCore.pyqtSignal(str, str)
  181. # File type and filename
  182. file_saved = QtCore.pyqtSignal(str, str)
  183. # Percentage of progress
  184. progress = QtCore.pyqtSignal(int)
  185. # Emitted when a new object has been added or deleted from/to the collection
  186. object_status_changed = QtCore.pyqtSignal(object, str, str)
  187. message = QtCore.pyqtSignal(str, str, str)
  188. # Emmited when shell command is finished(one command only)
  189. shell_command_finished = QtCore.pyqtSignal(object)
  190. # Emitted when multiprocess pool has been recreated
  191. pool_recreated = QtCore.pyqtSignal(object)
  192. # Emitted when an unhandled exception happens
  193. # in the worker task.
  194. thread_exception = QtCore.pyqtSignal(object)
  195. # used to signal that there are arguments for the app
  196. args_at_startup = QtCore.pyqtSignal(list)
  197. # a reusable signal to replot a list of objects
  198. # should be disconnected after use so it can be reused
  199. replot_signal = pyqtSignal(list)
  200. # signal emitted when jumping
  201. jump_signal = pyqtSignal(tuple)
  202. # signal emitted when jumping
  203. locate_signal = pyqtSignal(tuple, str)
  204. # close app signal
  205. close_app_signal = pyqtSignal()
  206. # will perform the cleanup operation after a Graceful Exit
  207. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  208. # graphic residues behind
  209. cleanup = pyqtSignal()
  210. def __init__(self, user_defaults=True):
  211. """
  212. Starts the application.
  213. :return: app
  214. :rtype: App
  215. """
  216. super().__init__()
  217. App.log.info("FlatCAM Starting...")
  218. self.main_thread = QtWidgets.QApplication.instance().thread()
  219. # ############################################################################################################
  220. # ################# Setup the listening thread for another instance launching with args ######################
  221. # ############################################################################################################
  222. if sys.platform == 'win32' or sys.platform == 'linux':
  223. # make sure the thread is stored by using a self. otherwise it's garbage collected
  224. self.th = QtCore.QThread()
  225. self.th.start(priority=QtCore.QThread.LowestPriority)
  226. self.new_launch = ArgsThread()
  227. self.new_launch.open_signal[list].connect(self.on_startup_args)
  228. self.new_launch.moveToThread(self.th)
  229. self.new_launch.start.emit()
  230. # ############################################################################################################
  231. # ########################################## OS-specific #####################################################
  232. # ############################################################################################################
  233. portable = False
  234. # Folder for user settings.
  235. if sys.platform == 'win32':
  236. if platform.architecture()[0] == '32bit':
  237. App.log.debug("Win32!")
  238. else:
  239. App.log.debug("Win64!")
  240. # #######################################################################################################
  241. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  242. # #######################################################################################################
  243. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  244. try:
  245. with open(config_file, 'r'):
  246. pass
  247. except FileNotFoundError:
  248. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  249. try:
  250. with open(config_file, 'r') as f:
  251. try:
  252. for line in f:
  253. param = str(line).replace('\n', '').rpartition('=')
  254. if param[0] == 'portable':
  255. try:
  256. portable = eval(param[2])
  257. except NameError:
  258. portable = False
  259. if param[0] == 'headless':
  260. if param[2].lower() == 'true':
  261. self.cmd_line_headless = 1
  262. else:
  263. self.cmd_line_headless = None
  264. except Exception as e:
  265. log.debug('App.__init__() -->%s' % str(e))
  266. return
  267. except FileNotFoundError as e:
  268. log.debug(str(e))
  269. pass
  270. if portable is False:
  271. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  272. else:
  273. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  274. self.os = 'windows'
  275. else: # Linux/Unix/MacOS
  276. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  277. self.os = 'unix'
  278. # ############################################################################################################
  279. # ################################# Setup folders and files ##################################################
  280. # ############################################################################################################
  281. if not os.path.exists(self.data_path):
  282. os.makedirs(self.data_path)
  283. App.log.debug('Created data folder: ' + self.data_path)
  284. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  285. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  286. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  287. if not os.path.exists(self.preprocessorpaths):
  288. os.makedirs(self.preprocessorpaths)
  289. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  290. # create geo_tools_db.FlatDB file if there is none
  291. try:
  292. f = open(self.data_path + '/geo_tools_db.FlatDB')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty geo_tool_db.FlatDB')
  296. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create current_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/current_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty current_defaults.FlatConfig')
  305. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # Write factory_defaults.FlatConfig file to disk
  309. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  310. # create a recent files json file if there is none
  311. try:
  312. f = open(self.data_path + '/recent.json')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty recent.json')
  316. f = open(self.data_path + '/recent.json', 'w')
  317. json.dump([], f)
  318. f.close()
  319. # create a recent projects json file if there is none
  320. try:
  321. fp = open(self.data_path + '/recent_projects.json')
  322. fp.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent_projects.json')
  325. fp = open(self.data_path + '/recent_projects.json', 'w')
  326. json.dump([], fp)
  327. fp.close()
  328. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. log.debug("Application path is " + self.app_home)
  332. log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform[str].connect(self.info)
  606. self.inform[str, bool].connect(self.info)
  607. # signal to be called when the app is quiting
  608. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  609. self.message.connect(lambda: message_dialog(parent=self.ui))
  610. # self.progress.connect(self.set_progress_bar)
  611. # signals emitted when file state change
  612. self.file_opened.connect(self.register_recent)
  613. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  614. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  615. # ########################################## Standard signals ###############################################
  616. # ### Menu
  617. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  618. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  619. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  620. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  621. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  622. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  623. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  624. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  625. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  626. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  627. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  628. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  629. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  630. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  631. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  632. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  633. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  634. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  635. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  636. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  637. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  638. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  639. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  640. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  641. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  642. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  643. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  644. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  645. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  646. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  647. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  648. self.ui.menufile_exit.triggered.connect(self.final_save)
  649. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  650. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  651. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  652. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  653. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  654. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  655. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  656. self.ui.menueditdelete.triggered.connect(self.on_delete)
  657. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  658. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  659. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  660. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  661. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  662. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  663. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  664. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  665. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  666. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  667. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  668. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  669. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  670. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  671. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  672. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  673. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  674. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  675. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  676. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  677. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  678. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  679. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  680. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  681. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  682. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  683. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  684. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  685. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  686. self.ui.menuview_replot.triggered.connect(self.plot_all)
  687. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  688. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  689. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  690. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  692. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  693. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  694. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  695. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  696. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  697. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  698. self.ui.menuhelp_about.triggered.connect(self.on_about)
  699. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  700. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  701. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  702. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  703. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  704. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  705. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  706. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  707. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  708. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  709. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  710. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  711. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  712. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  713. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  714. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  715. # ToolBar signals
  716. self.connect_toolbar_signals()
  717. # Notebook and Plot Tab Area signals
  718. # make the right click on the notebook tab and plot tab area tab raise a menu
  719. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. self.on_tab_setup_context_menu()
  722. # activate initial state
  723. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  724. # Context Menu
  725. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  726. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  727. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  728. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  729. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  730. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  731. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  732. self.ui.clearplot.triggered.connect(self.clear_plots)
  733. self.ui.replot.triggered.connect(self.plot_all)
  734. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  735. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  736. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  737. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  738. self.ui.popmenu_move.triggered.connect(self.obj_move)
  739. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  740. # Project Context Menu -> Color Setting
  741. for act in self.ui.menuprojectcolor.actions():
  742. act.triggered.connect(self.on_set_color_action_triggered)
  743. # ###########################################################################################################
  744. # #################################### GUI PREFERENCES SIGNALS ##############################################
  745. # ###########################################################################################################
  746. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  747. lambda: self.on_toggle_units(no_pref=False))
  748. # ##################################### Workspace Setting Signals ###########################################
  749. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  750. self.on_workspace_modified)
  751. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  752. self.on_workspace_modified
  753. )
  754. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  755. # ###########################################################################################################
  756. # ######################################## GUI SETTINGS SIGNALS #############################################
  757. # ###########################################################################################################
  758. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  759. # ######################################## Tools related signals ############################################
  760. # portability changed signal
  761. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  762. # Object list
  763. self.object_status_changed.connect(self.collection.on_collection_updated)
  764. # when there are arguments at application startup this get launched
  765. self.args_at_startup[list].connect(self.on_startup_args)
  766. # ###########################################################################################################
  767. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  768. # ###########################################################################################################
  769. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  770. lambda: self.restore_extensions(ext_type='excellon'))
  771. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  772. lambda: self.restore_extensions(ext_type='gcode'))
  773. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  774. lambda: self.restore_extensions(ext_type='gerber'))
  775. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  776. lambda: self.delete_all_extensions(ext_type='excellon'))
  777. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  778. lambda: self.delete_all_extensions(ext_type='gcode'))
  779. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  780. lambda: self.delete_all_extensions(ext_type='gerber'))
  781. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  782. lambda: self.add_extension(ext_type='excellon'))
  783. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  784. lambda: self.add_extension(ext_type='gcode'))
  785. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  786. lambda: self.add_extension(ext_type='gerber'))
  787. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  788. lambda: self.del_extension(ext_type='excellon'))
  789. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  790. lambda: self.del_extension(ext_type='gcode'))
  791. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  792. lambda: self.del_extension(ext_type='gerber'))
  793. # connect the 'Apply' buttons from the Preferences/File Associations
  794. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  795. lambda: self.on_register_files(obj_type='excellon'))
  796. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  797. lambda: self.on_register_files(obj_type='gcode'))
  798. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  799. lambda: self.on_register_files(obj_type='gerber'))
  800. # ###########################################################################################################
  801. # ########################################### KEYWORDS SIGNALS ##############################################
  802. # ###########################################################################################################
  803. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  804. lambda: self.restore_extensions(ext_type='keyword'))
  805. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  806. lambda: self.delete_all_extensions(ext_type='keyword'))
  807. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  808. lambda: self.add_extension(ext_type='keyword'))
  809. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  810. lambda: self.del_extension(ext_type='keyword'))
  811. # ###########################################################################################################
  812. # ########################################### GUI SIGNALS ###################################################
  813. # ###########################################################################################################
  814. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  815. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  816. # ###########################################################################################################
  817. # ####################################### VARIOUS SIGNALS ###################################################
  818. # ###########################################################################################################
  819. # connect the abort_all_tasks related slots to the related signals
  820. self.proc_container.idle_flag.connect(self.app_is_idle)
  821. # signal emitted when a tab is closed in the Plot Area
  822. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  823. # signal to close the application
  824. self.close_app_signal.connect(self.kill_app)
  825. # ################################# FINISHED CONNECTING SIGNALS #############################################
  826. # ###########################################################################################################
  827. # ###########################################################################################################
  828. # ###########################################################################################################
  829. self.log.debug("Finished connecting Signals.")
  830. # ###########################################################################################################
  831. # ########################################## Other setups ###################################################
  832. # ###########################################################################################################
  833. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  834. # depending on from where those tools are called different actions can be done
  835. self.call_source = 'app'
  836. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  837. self.tool_tab_locked = False
  838. # decide if to show or hide the Notebook side of the screen at startup
  839. if self.defaults["global_project_at_startup"] is True:
  840. self.ui.splitter.setSizes([1, 1])
  841. else:
  842. self.ui.splitter.setSizes([0, 1])
  843. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  844. self.setup_component_editor()
  845. # ###########################################################################################################
  846. # ####################################### Auto-complete KEYWORDS ############################################
  847. # ###########################################################################################################
  848. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  849. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  850. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  851. 'export_exc',
  852. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  853. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  854. 'interiors', 'isolate', 'join_excellon',
  855. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  856. 'mirror', 'ncc',
  857. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  858. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  859. 'options', 'origin',
  860. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  861. 'save', 'save_project',
  862. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  863. 'skew', 'subtract_poly', 'subtract_rectangle',
  864. 'version', 'write_gcode'
  865. ]
  866. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  867. 'Paste_1',
  868. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  869. 'Toolchange_manual', 'True', 'Users',
  870. 'all', 'auto', 'axis',
  871. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  872. 'contour', 'default',
  873. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  874. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  875. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  876. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  877. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  878. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  879. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  880. 'spacing_columns',
  881. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  882. 'toolchange_xy', 'toolchangez', 'travelz',
  883. 'tooldia', 'use_threads', 'value',
  884. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  885. ]
  886. self.tcl_keywords = [
  887. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  888. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  889. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  890. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  891. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  892. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  893. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  894. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  895. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  896. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  897. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  898. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  899. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  900. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  901. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  902. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  903. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  904. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  905. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  906. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  907. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  908. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  909. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  910. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  911. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  912. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  913. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  914. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  915. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  916. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  917. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  918. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  919. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  920. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  921. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  922. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  923. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  924. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  925. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  926. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  927. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  928. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  929. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  930. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  931. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  932. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  933. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  934. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  935. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  936. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  937. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  938. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  939. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  940. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  941. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  942. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  943. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  944. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  945. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  946. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  947. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  948. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  949. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  950. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  951. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  952. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  953. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  954. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  955. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  956. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  957. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  958. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  959. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  960. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  961. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  962. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  963. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  964. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  965. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  966. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  967. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  968. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  969. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  970. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  971. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  972. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  973. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  974. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  975. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  976. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  977. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  978. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  979. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  980. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  981. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  982. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  983. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  984. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  985. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  986. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  987. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  988. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  989. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  990. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  991. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  992. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  993. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  994. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  995. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  996. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  997. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  998. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  999. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1000. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1001. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1002. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1003. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1004. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1005. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1006. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1007. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1008. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1009. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1010. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1011. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1012. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1013. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1014. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1015. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1016. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1017. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1018. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1019. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1020. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1021. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1022. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1023. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1024. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1025. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1026. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1027. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1028. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1029. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1030. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1031. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1032. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1033. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1034. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1035. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1036. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1037. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1038. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1039. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1040. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1041. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1042. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1043. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1044. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1045. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1046. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1047. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1048. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1049. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1050. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1051. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1052. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1053. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1054. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1055. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1056. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1057. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1058. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1059. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1060. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1061. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1062. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1063. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1064. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1065. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1066. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1067. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1068. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1069. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1070. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1071. ]
  1072. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1073. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1074. # ###########################################################################################################
  1075. # ############################################## Shell SETUP ################################################
  1076. # ###########################################################################################################
  1077. self.shell = FCShell(app=self, version=self.version)
  1078. self.ui.shell_dock.setWidget(self.shell)
  1079. self.log.debug("TCL Shell has been initialized.")
  1080. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1081. if self.defaults["global_shell_at_startup"]:
  1082. self.ui.shell_dock.show()
  1083. else:
  1084. self.ui.shell_dock.hide()
  1085. # ###########################################################################################################
  1086. # ########################################## Tools and Plugins ##############################################
  1087. # ###########################################################################################################
  1088. self.dblsidedtool = None
  1089. self.distance_tool = None
  1090. self.distance_min_tool = None
  1091. self.panelize_tool = None
  1092. self.film_tool = None
  1093. self.paste_tool = None
  1094. self.calculator_tool = None
  1095. self.rules_tool = None
  1096. self.sub_tool = None
  1097. self.move_tool = None
  1098. self.cutout_tool = None
  1099. self.ncclear_tool = None
  1100. self.paint_tool = None
  1101. self.isolation_tool = None
  1102. self.optimal_tool = None
  1103. self.transform_tool = None
  1104. self.properties_tool = None
  1105. self.pdf_tool = None
  1106. self.image_tool = None
  1107. self.pcb_wizard_tool = None
  1108. self.cal_exc_tool = None
  1109. self.qrcode_tool = None
  1110. self.copper_thieving_tool = None
  1111. self.fiducial_tool = None
  1112. self.edrills_tool = None
  1113. self.align_objects_tool = None
  1114. self.punch_tool = None
  1115. self.invert_tool = None
  1116. self.corners_tool = None
  1117. self.etch_tool = None
  1118. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1119. try:
  1120. self.install_tools()
  1121. except AttributeError as e:
  1122. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1123. # ###########################################################################################################
  1124. # ############################################ SETUP RECENT ITEMS ###########################################
  1125. # ###########################################################################################################
  1126. self.setup_recent_items()
  1127. # ###########################################################################################################
  1128. # ######################################### BookMarks Manager ###############################################
  1129. # ###########################################################################################################
  1130. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1131. self.install_bookmarks()
  1132. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1133. # ###########################################################################################################
  1134. # ########################################### Tools Database ################################################
  1135. # ###########################################################################################################
  1136. self.tools_db_tab = None
  1137. # ### System Font Parsing ###
  1138. # self.f_parse = ParseFont(self)
  1139. # self.parse_system_fonts()
  1140. # ###########################################################################################################
  1141. # ######################################### Check for updates ###############################################
  1142. # ###########################################################################################################
  1143. # Separate thread (Not worker)
  1144. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1145. if (self.beta is False or self.beta is None) and \
  1146. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1147. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1148. # self.thr2 = QtCore.QThread()
  1149. self.worker_task.emit({'fcn': self.version_check,
  1150. 'params': []})
  1151. # self.thr2.start(QtCore.QThread.LowPriority)
  1152. # ###########################################################################################################
  1153. # ##################################### Register files with FlatCAM; #######################################
  1154. # ################################### It works only for Windows for now ####################################
  1155. # ###########################################################################################################
  1156. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1157. self.on_register_files()
  1158. # ###########################################################################################################
  1159. # ######################################## Variables for global usage #######################################
  1160. # ###########################################################################################################
  1161. # hold the App units
  1162. self.units = 'MM'
  1163. # coordinates for relative position display
  1164. self.rel_point1 = (0, 0)
  1165. self.rel_point2 = (0, 0)
  1166. # variable to store coordinates
  1167. self.pos = (0, 0)
  1168. self.pos_canvas = (0, 0)
  1169. self.pos_jump = (0, 0)
  1170. # variable to store mouse coordinates
  1171. self.mouse = [0, 0]
  1172. # variable to store the delta positions on cavnas
  1173. self.dx = 0
  1174. self.dy = 0
  1175. # decide if we have a double click or single click
  1176. self.doubleclick = False
  1177. # store here the is_dragging value
  1178. self.event_is_dragging = False
  1179. # variable to store if a command is active (then the var is not None) and which one it is
  1180. self.command_active = None
  1181. # variable to store the status of moving selection action
  1182. # None value means that it's not an selection action
  1183. # True value = a selection from left to right
  1184. # False value = a selection from right to left
  1185. self.selection_type = None
  1186. # List to store the objects that are currently loaded in FlatCAM
  1187. # This list is updated on each object creation or object delete
  1188. self.all_objects_list = []
  1189. self.objects_under_the_click_list = []
  1190. # List to store the objects that are selected
  1191. self.sel_objects_list = []
  1192. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1193. self.key_modifiers = None
  1194. # Variable to store the status of the code editor
  1195. self.toggle_codeeditor = False
  1196. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1197. self.click_noproject = False
  1198. self.cursor = None
  1199. # Variable to store the GCODE that was edited
  1200. self.gcode_edited = ""
  1201. self.text_editor_tab = None
  1202. # reference for the self.ui.code_editor
  1203. self.reference_code_editor = None
  1204. self.script_code = ''
  1205. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1206. self.tools_db_changed_flag = False
  1207. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1208. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1209. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1210. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1211. 'tsm']
  1212. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1213. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1214. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1215. 'sbp', 'tap', 'xpi']
  1216. self.svg_list = ['svg']
  1217. self.dxf_list = ['dxf']
  1218. self.pdf_list = ['pdf']
  1219. self.prj_list = ['flatprj']
  1220. self.conf_list = ['flatconfig']
  1221. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1222. # flag for polygons not cleared
  1223. self.poly_not_cleared = False
  1224. # VisPy visuals
  1225. self.isHovering = False
  1226. self.notHovering = True
  1227. # Window geometry
  1228. self.x_pos = None
  1229. self.y_pos = None
  1230. self.width = None
  1231. self.height = None
  1232. # when True, the app has to return from any thread
  1233. self.abort_flag = False
  1234. # set the value used in the Windows Title
  1235. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1236. # this holds a widget that is installed in the Plot Area when View Source option is used
  1237. self.source_editor_tab = None
  1238. self.pagesize = {}
  1239. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1240. # VisPy visuals
  1241. if self.is_legacy is False:
  1242. try:
  1243. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1244. except AttributeError:
  1245. self.tool_shapes = None
  1246. else:
  1247. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1248. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1249. # used in the delayed shutdown self.start_delayed_quit() method
  1250. self.save_timer = None
  1251. # ###########################################################################################################
  1252. # ################################## ADDING FlatCAM EDITORS section #########################################
  1253. # ###########################################################################################################
  1254. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1255. # at the first launch of the App , the editors will not be functional.
  1256. try:
  1257. self.geo_editor = FlatCAMGeoEditor(self)
  1258. except AttributeError:
  1259. pass
  1260. try:
  1261. self.exc_editor = FlatCAMExcEditor(self)
  1262. except AttributeError:
  1263. pass
  1264. try:
  1265. self.grb_editor = FlatCAMGrbEditor(self)
  1266. except AttributeError:
  1267. pass
  1268. self.log.debug("Finished adding FlatCAM Editor's.")
  1269. self.set_ui_title(name=_("New Project - Not saved"))
  1270. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1271. current_platform = platform.architecture()[0]
  1272. if current_platform != '64bit':
  1273. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1274. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1275. # ###########################################################################################################
  1276. # ########################################### EXCLUSION AREAS ###############################################
  1277. # ###########################################################################################################
  1278. self.exc_areas = ExclusionAreas(app=self)
  1279. # ###########################################################################################################
  1280. # ##################################### Finished the CONSTRUCTOR ############################################
  1281. # ###########################################################################################################
  1282. App.log.debug("END of constructor. Releasing control.")
  1283. # ###########################################################################################################
  1284. # ########################################## SHOW GUI #######################################################
  1285. # ###########################################################################################################
  1286. # if the app is not started as headless, show it
  1287. if self.cmd_line_headless != 1:
  1288. if show_splash:
  1289. # finish the splash
  1290. self.splash.finish(self.ui)
  1291. mgui_settings = QSettings("Open Source", "FlatCAM")
  1292. if mgui_settings.contains("maximized_gui"):
  1293. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1294. if maximized_ui is True:
  1295. self.ui.showMaximized()
  1296. else:
  1297. self.ui.show()
  1298. else:
  1299. self.ui.show()
  1300. if self.defaults["global_systray_icon"]:
  1301. self.trayIcon.show()
  1302. else:
  1303. log.warning("******************* RUNNING HEADLESS *******************")
  1304. # ###########################################################################################################
  1305. # ######################################## START-UP ARGUMENTS ###############################################
  1306. # ###########################################################################################################
  1307. # test if the program was started with a script as parameter
  1308. if self.cmd_line_shellvar:
  1309. try:
  1310. cnt = 0
  1311. command_tcl = 0
  1312. for i in self.cmd_line_shellvar.split(','):
  1313. if i is not None:
  1314. # noinspection PyBroadException
  1315. try:
  1316. command_tcl = eval(i)
  1317. except Exception:
  1318. command_tcl = i
  1319. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1320. cnt += 1
  1321. # if there are Windows paths then replace the path separator with a Unix like one
  1322. if sys.platform == 'win32':
  1323. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1324. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1325. except Exception as ext:
  1326. print("ERROR: ", ext)
  1327. sys.exit(2)
  1328. if self.cmd_line_shellfile:
  1329. if self.cmd_line_headless != 1:
  1330. if self.ui.shell_dock.isHidden():
  1331. self.ui.shell_dock.show()
  1332. try:
  1333. with open(self.cmd_line_shellfile, "r") as myfile:
  1334. # if show_splash:
  1335. # self.splash.showMessage('%s: %ssec\n%s' % (
  1336. # _("Canvas initialization started.\n"
  1337. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1338. # _("Executing Tcl Script ...")),
  1339. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1340. # color=QtGui.QColor("gray"))
  1341. cmd_line_shellfile_text = myfile.read()
  1342. if self.cmd_line_headless != 1:
  1343. self.shell.exec_command(cmd_line_shellfile_text)
  1344. else:
  1345. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1346. except Exception as ext:
  1347. print("ERROR: ", ext)
  1348. sys.exit(2)
  1349. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1350. # the path/file_name must be enclosed in quotes if it contain spaces
  1351. if App.args:
  1352. self.args_at_startup.emit(App.args)
  1353. if self.defaults.old_defaults_found is True:
  1354. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1355. "Please reboot the application to update."))
  1356. self.defaults.old_defaults_found = False
  1357. # ######################################### INIT FINISHED #######################################################
  1358. # #################################################################################################################
  1359. # #################################################################################################################
  1360. # #################################################################################################################
  1361. # #################################################################################################################
  1362. # #################################################################################################################
  1363. @staticmethod
  1364. def copy_and_overwrite(from_path, to_path):
  1365. """
  1366. From here:
  1367. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1368. :param from_path: source path
  1369. :param to_path: destination path
  1370. :return: None
  1371. """
  1372. if os.path.exists(to_path):
  1373. shutil.rmtree(to_path)
  1374. try:
  1375. shutil.copytree(from_path, to_path)
  1376. except FileNotFoundError:
  1377. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1378. shutil.copytree(from_new_path, to_path)
  1379. def on_startup_args(self, args, silent=False):
  1380. """
  1381. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1382. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1383. :param args: a list containing the application args at startup
  1384. :return: None
  1385. """
  1386. if args is not None:
  1387. args_to_process = args
  1388. else:
  1389. args_to_process = App.args
  1390. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1391. for argument in args_to_process:
  1392. if '.FlatPrj'.lower() in argument.lower():
  1393. try:
  1394. project_name = str(argument)
  1395. if project_name == "":
  1396. if silent is False:
  1397. self.inform.emit(_("Cancelled."))
  1398. else:
  1399. # self.open_project(project_name)
  1400. run_from_arg = True
  1401. # self.worker_task.emit({'fcn': self.open_project,
  1402. # 'params': [project_name, run_from_arg]})
  1403. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1404. except Exception as e:
  1405. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1406. elif '.FlatConfig'.lower() in argument.lower():
  1407. try:
  1408. file_name = str(argument)
  1409. if file_name == "":
  1410. if silent is False:
  1411. self.inform.emit(_("Open Config file failed."))
  1412. else:
  1413. run_from_arg = True
  1414. # self.worker_task.emit({'fcn': self.open_config_file,
  1415. # 'params': [file_name, run_from_arg]})
  1416. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1417. except Exception as e:
  1418. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1419. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1420. try:
  1421. file_name = str(argument)
  1422. if file_name == "":
  1423. if silent is False:
  1424. self.inform.emit(_("Open Script file failed."))
  1425. else:
  1426. if silent is False:
  1427. self.on_fileopenscript(name=file_name)
  1428. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1429. self.on_filerunscript(name=file_name)
  1430. except Exception as e:
  1431. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1432. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1433. log.debug("App.on_startup_args() --> Quit event.")
  1434. sys.exit()
  1435. elif 'save'.lower() in argument.lower():
  1436. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1437. self.preferencesUiManager.save_defaults()
  1438. else:
  1439. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1440. proc_arg = argument.lower()
  1441. for ext in exc_list:
  1442. proc_ext = ext.replace(' ', '')
  1443. proc_ext = '.%s' % proc_ext
  1444. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1445. file_name = str(argument)
  1446. if file_name == "":
  1447. if silent is False:
  1448. self.inform.emit(_("Open Excellon file failed."))
  1449. else:
  1450. self.on_fileopenexcellon(name=file_name, signal=None)
  1451. return
  1452. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1453. for ext in gco_list:
  1454. proc_ext = ext.replace(' ', '')
  1455. proc_ext = '.%s' % proc_ext
  1456. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1457. file_name = str(argument)
  1458. if file_name == "":
  1459. if silent is False:
  1460. self.inform.emit(_("Open GCode file failed."))
  1461. else:
  1462. self.on_fileopengcode(name=file_name, signal=None)
  1463. return
  1464. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1465. for ext in grb_list:
  1466. proc_ext = ext.replace(' ', '')
  1467. proc_ext = '.%s' % proc_ext
  1468. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1469. file_name = str(argument)
  1470. if file_name == "":
  1471. if silent is False:
  1472. self.inform.emit(_("Open Gerber file failed."))
  1473. else:
  1474. self.on_fileopengerber(name=file_name, signal=None)
  1475. return
  1476. # if it reached here without already returning then the app was registered with a file that it does not
  1477. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1478. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1479. # for arg in args_to_process:
  1480. # if 'FlatCAM.exe' in arg:
  1481. # continue
  1482. # else:
  1483. # sys.exit(2)
  1484. def set_ui_title(self, name):
  1485. """
  1486. Sets the title of the main window.
  1487. :param name: String that store the project path and project name
  1488. :return: None
  1489. """
  1490. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1491. (self.version,
  1492. ('BETA' if self.beta else ''),
  1493. platform.architecture()[0],
  1494. self.engine,
  1495. name)
  1496. )
  1497. def on_app_restart(self):
  1498. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1499. # be left in the SySTray
  1500. try:
  1501. self.trayIcon.hide()
  1502. except Exception:
  1503. pass
  1504. fcTranslate.restart_program(app=self)
  1505. def clear_pool(self):
  1506. """
  1507. Clear the multiprocessing pool and calls garbage collector.
  1508. :return: None
  1509. """
  1510. self.pool.close()
  1511. self.pool = Pool()
  1512. self.pool_recreated.emit(self.pool)
  1513. gc.collect()
  1514. def install_tools(self):
  1515. """
  1516. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1517. Instantiation of the Tools classes.
  1518. The order that the tools are installed is important as they can depend on each other install position.
  1519. :return: None
  1520. """
  1521. self.distance_tool = Distance(self)
  1522. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1523. before=self.ui.menueditorigin,
  1524. separator=False)
  1525. self.distance_min_tool = DistanceMin(self)
  1526. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1527. pos=self.ui.menuedit,
  1528. before=self.ui.menueditorigin,
  1529. separator=True)
  1530. self.dblsidedtool = DblSidedTool(self)
  1531. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1532. self.cal_exc_tool = ToolCalibration(self)
  1533. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1534. before=self.dblsidedtool.menuAction,
  1535. separator=False)
  1536. self.align_objects_tool = AlignObjects(self)
  1537. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1538. self.edrills_tool = ToolExtractDrills(self)
  1539. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1540. self.panelize_tool = Panelize(self)
  1541. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1542. self.film_tool = Film(self)
  1543. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1544. self.paste_tool = SolderPaste(self)
  1545. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1546. self.calculator_tool = ToolCalculator(self)
  1547. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1548. self.sub_tool = ToolSub(self)
  1549. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1550. pos=self.ui.menutool, separator=True)
  1551. self.rules_tool = RulesCheck(self)
  1552. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1553. pos=self.ui.menutool, separator=False)
  1554. self.optimal_tool = ToolOptimal(self)
  1555. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1556. pos=self.ui.menutool, separator=True)
  1557. self.move_tool = ToolMove(self)
  1558. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1559. before=self.ui.menueditorigin, separator=True)
  1560. self.cutout_tool = CutOut(self)
  1561. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1562. before=self.sub_tool.menuAction)
  1563. self.ncclear_tool = NonCopperClear(self)
  1564. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1565. before=self.sub_tool.menuAction, separator=True)
  1566. self.paint_tool = ToolPaint(self)
  1567. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1568. before=self.sub_tool.menuAction, separator=True)
  1569. self.isolation_tool = ToolIsolation(self)
  1570. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1571. before=self.sub_tool.menuAction, separator=True)
  1572. self.copper_thieving_tool = ToolCopperThieving(self)
  1573. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1574. pos=self.ui.menutool)
  1575. self.fiducial_tool = ToolFiducials(self)
  1576. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1577. pos=self.ui.menutool)
  1578. self.qrcode_tool = QRCode(self)
  1579. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1580. pos=self.ui.menutool)
  1581. self.punch_tool = ToolPunchGerber(self)
  1582. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1583. self.invert_tool = ToolInvertGerber(self)
  1584. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1585. self.corners_tool = ToolCorners(self)
  1586. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1587. self.etch_tool = ToolEtchCompensation(self)
  1588. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1589. self.transform_tool = ToolTransform(self)
  1590. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1591. pos=self.ui.menuoptions, separator=True)
  1592. self.properties_tool = Properties(self)
  1593. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1594. pos=self.ui.menuoptions)
  1595. self.pdf_tool = ToolPDF(self)
  1596. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1597. pos=self.ui.menufileimport,
  1598. separator=True)
  1599. self.image_tool = ToolImage(self)
  1600. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1601. pos=self.ui.menufileimport,
  1602. separator=True)
  1603. self.pcb_wizard_tool = PcbWizard(self)
  1604. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1605. pos=self.ui.menufileimport)
  1606. self.log.debug("Tools are installed.")
  1607. def remove_tools(self):
  1608. """
  1609. Will remove all the actions in the Tool menu.
  1610. :return: None
  1611. """
  1612. for act in self.ui.menutool.actions():
  1613. self.ui.menutool.removeAction(act)
  1614. def init_tools(self):
  1615. """
  1616. Initialize the Tool tab in the notebook side of the central widget.
  1617. Remove the actions in the Tools menu.
  1618. Instantiate again the FlatCAM tools (plugins).
  1619. All this is required when changing the layout: standard, compact etc.
  1620. :return: None
  1621. """
  1622. log.debug("init_tools()")
  1623. # delete the data currently in the Tools Tab and the Tab itself
  1624. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1625. if widget is not None:
  1626. widget.deleteLater()
  1627. self.ui.notebook.removeTab(2)
  1628. # rebuild the Tools Tab
  1629. self.ui.tool_tab = QtWidgets.QWidget()
  1630. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1631. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1632. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1633. self.ui.tool_scroll_area = VerticalScrollArea()
  1634. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1635. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1636. # first remove all of them
  1637. self.remove_tools()
  1638. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1639. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1640. '&Command Line\tS')
  1641. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1642. # third install all of them
  1643. try:
  1644. self.install_tools()
  1645. except AttributeError:
  1646. pass
  1647. self.log.debug("Tools are initialized.")
  1648. # def parse_system_fonts(self):
  1649. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1650. # 'params': []})
  1651. def connect_toolbar_signals(self):
  1652. """
  1653. Reconnect the signals to the actions in the toolbar.
  1654. This has to be done each time after the FlatCAM tools are removed/installed.
  1655. :return: None
  1656. """
  1657. # Toolbar
  1658. # File Toolbar Signals
  1659. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1660. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1661. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1662. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1663. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1664. # View Toolbar Signals
  1665. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1666. self.ui.replot_btn.triggered.connect(self.plot_all)
  1667. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1668. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1669. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1670. # Edit Toolbar Signals
  1671. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1672. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1673. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1674. self.ui.delete_btn.triggered.connect(self.on_delete)
  1675. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1676. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1677. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1678. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1679. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1680. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1681. # Scripting Toolbar Signals
  1682. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1683. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1684. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1685. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1686. # Tools Toolbar Signals
  1687. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1688. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1689. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1690. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1691. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1692. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1693. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1694. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1695. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1696. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1697. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1698. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1699. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1700. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1701. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1702. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1703. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1704. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1705. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1706. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1707. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1708. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1709. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1710. def object2editor(self):
  1711. """
  1712. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1713. :return: None
  1714. """
  1715. self.defaults.report_usage("object2editor()")
  1716. # disable the objects menu as it may interfere with the AppEditors
  1717. self.ui.menuobjects.setDisabled(True)
  1718. edited_object = self.collection.get_active()
  1719. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1720. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1721. pass
  1722. else:
  1723. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1724. return
  1725. if isinstance(edited_object, GeometryObject):
  1726. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1727. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1728. # we set the notebook to hidden
  1729. # self.ui.splitter.setSizes([0, 1])
  1730. if edited_object.multigeo is True:
  1731. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1732. if len(sel_rows) > 1:
  1733. self.inform.emit('[WARNING_NOTCL] %s' %
  1734. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1735. "is not possible.\n"
  1736. "Edit only one geometry at a time."))
  1737. # determine the tool dia of the selected tool
  1738. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1739. # now find the key in the edited_object.tools that has this tooldia
  1740. multi_tool = 1
  1741. for tool in edited_object.tools:
  1742. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1743. multi_tool = tool
  1744. break
  1745. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1746. else:
  1747. self.geo_editor.edit_fcgeometry(edited_object)
  1748. # set call source to the Editor we go into
  1749. self.call_source = 'geo_editor'
  1750. elif isinstance(edited_object, ExcellonObject):
  1751. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1752. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1753. if self.ui.splitter.sizes()[0] == 0:
  1754. self.ui.splitter.setSizes([1, 1])
  1755. self.exc_editor.edit_fcexcellon(edited_object)
  1756. # set call source to the Editor we go into
  1757. self.call_source = 'exc_editor'
  1758. elif isinstance(edited_object, GerberObject):
  1759. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1760. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1761. if self.ui.splitter.sizes()[0] == 0:
  1762. self.ui.splitter.setSizes([1, 1])
  1763. self.grb_editor.edit_fcgerber(edited_object)
  1764. # set call source to the Editor we go into
  1765. self.call_source = 'grb_editor'
  1766. # reset the following variables so the UI is built again after edit
  1767. edited_object.ui_build = False
  1768. edited_object.build_aperture_storage = False
  1769. elif isinstance(edited_object, CNCJobObject):
  1770. if self.ui.splitter.sizes()[0] == 0:
  1771. self.ui.splitter.setSizes([1, 1])
  1772. edited_object.on_edit_code_click()
  1773. return
  1774. # make sure that we can't select another object while in Editor Mode:
  1775. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1776. self.ui.project_frame.setDisabled(True)
  1777. # delete any selection shape that might be active as they are not relevant in Editor
  1778. self.delete_selection_shape()
  1779. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1780. self.ui.plot_tab_area.protectTab(0)
  1781. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1782. self.should_we_save = True
  1783. def editor2object(self, cleanup=None):
  1784. """
  1785. Transfers the Geometry or Excellon from it's editor to the current object.
  1786. :return: None
  1787. """
  1788. self.defaults.report_usage("editor2object()")
  1789. # re-enable the objects menu that was disabled on entry in Editor mode
  1790. self.ui.menuobjects.setDisabled(False)
  1791. # do not update a geometry or excellon object unless it comes out of an editor
  1792. if self.call_source != 'app':
  1793. edited_obj = self.collection.get_active()
  1794. if cleanup is None:
  1795. msgbox = QtWidgets.QMessageBox()
  1796. msgbox.setText(_("Do you want to save the edited object?"))
  1797. msgbox.setWindowTitle(_("Close Editor"))
  1798. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1799. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1800. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1801. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1802. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1803. msgbox.setDefaultButton(bt_yes)
  1804. msgbox.exec_()
  1805. response = msgbox.clickedButton()
  1806. if response == bt_yes:
  1807. # clean the Tools Tab
  1808. self.ui.tool_scroll_area.takeWidget()
  1809. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1810. self.ui.notebook.setTabText(2, "Tool")
  1811. if isinstance(edited_obj, GeometryObject):
  1812. obj_type = "Geometry"
  1813. self.geo_editor.update_fcgeometry(edited_obj)
  1814. # self.geo_editor.update_options(edited_obj)
  1815. # restore GUI to the Selected TAB
  1816. # Remove anything else in the AppGUI
  1817. self.ui.tool_scroll_area.takeWidget()
  1818. # update the geo object options so it is including the bounding box values
  1819. try:
  1820. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1821. edited_obj.options['xmin'] = xmin
  1822. edited_obj.options['ymin'] = ymin
  1823. edited_obj.options['xmax'] = xmax
  1824. edited_obj.options['ymax'] = ymax
  1825. except AttributeError as e:
  1826. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1827. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1828. edited_obj.build_ui()
  1829. edited_obj.plot()
  1830. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1831. elif isinstance(edited_obj, GerberObject):
  1832. obj_type = "Gerber"
  1833. self.grb_editor.update_fcgerber()
  1834. # self.grb_editor.update_options(edited_obj)
  1835. # delete the old object (the source object) if it was an empty one
  1836. try:
  1837. if len(edited_obj.solid_geometry) == 0:
  1838. old_name = edited_obj.options['name']
  1839. self.collection.delete_by_name(old_name)
  1840. except TypeError:
  1841. # if the solid_geometry is a single Polygon the len() will not work
  1842. # in any case, falling here means that we have something in the solid_geometry, even if only
  1843. # a single Polygon, therefore we pass this
  1844. pass
  1845. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1846. # restore GUI to the Selected TAB
  1847. # Remove anything else in the AppGUI
  1848. self.ui.selected_scroll_area.takeWidget()
  1849. elif isinstance(edited_obj, ExcellonObject):
  1850. obj_type = "Excellon"
  1851. self.exc_editor.update_fcexcellon(edited_obj)
  1852. # self.exc_editor.update_options(edited_obj)
  1853. # restore GUI to the Selected TAB
  1854. # Remove anything else in the AppGUI
  1855. self.ui.tool_scroll_area.takeWidget()
  1856. # delete the old object (the source object) if it was an empty one
  1857. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1858. old_name = edited_obj.options['name']
  1859. self.collection.delete_by_name(name=old_name)
  1860. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1861. else:
  1862. self.inform.emit('[WARNING_NOTCL] %s' %
  1863. _("Select a Gerber, Geometry or Excellon Object to update."))
  1864. return
  1865. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1866. elif response == bt_no:
  1867. # clean the Tools Tab
  1868. self.ui.tool_scroll_area.takeWidget()
  1869. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1870. self.ui.notebook.setTabText(2, "Tool")
  1871. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1872. if isinstance(edited_obj, GeometryObject):
  1873. self.geo_editor.deactivate()
  1874. edited_obj.build_ui()
  1875. edited_obj.plot()
  1876. elif isinstance(edited_obj, GerberObject):
  1877. self.grb_editor.deactivate_grb_editor()
  1878. edited_obj.build_ui()
  1879. elif isinstance(edited_obj, ExcellonObject):
  1880. self.exc_editor.deactivate()
  1881. edited_obj.build_ui()
  1882. else:
  1883. self.inform.emit('[WARNING_NOTCL] %s' %
  1884. _("Select a Gerber, Geometry or Excellon Object to update."))
  1885. return
  1886. elif response == bt_cancel:
  1887. return
  1888. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1889. # edited_obj.build_ui()
  1890. # Switch notebook to Selected page
  1891. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1892. else:
  1893. if isinstance(edited_obj, GeometryObject):
  1894. self.geo_editor.deactivate()
  1895. elif isinstance(edited_obj, GerberObject):
  1896. self.grb_editor.deactivate_grb_editor()
  1897. elif isinstance(edited_obj, ExcellonObject):
  1898. self.exc_editor.deactivate()
  1899. else:
  1900. self.inform.emit('[WARNING_NOTCL] %s' %
  1901. _("Select a Gerber, Geometry or Excellon Object to update."))
  1902. return
  1903. # if notebook is hidden we show it
  1904. if self.ui.splitter.sizes()[0] == 0:
  1905. self.ui.splitter.setSizes([1, 1])
  1906. # restore the call_source to app
  1907. self.call_source = 'app'
  1908. # edited_obj.plot()
  1909. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1910. self.ui.plot_tab_area.protectTab(0)
  1911. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1912. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1913. self.ui.project_frame.setDisabled(False)
  1914. def get_last_folder(self):
  1915. """
  1916. Get the folder path from where the last file was opened.
  1917. :return: String, last opened folder path
  1918. """
  1919. return self.defaults["global_last_folder"]
  1920. def get_last_save_folder(self):
  1921. """
  1922. Get the folder path from where the last file was saved.
  1923. :return: String, last saved folder path
  1924. """
  1925. loc = self.defaults["global_last_save_folder"]
  1926. if loc is None:
  1927. loc = self.defaults["global_last_folder"]
  1928. if loc is None:
  1929. loc = os.path.dirname(__file__)
  1930. return loc
  1931. @QtCore.pyqtSlot(str)
  1932. @QtCore.pyqtSlot(str, bool)
  1933. def info(self, msg, shell_echo=True):
  1934. """
  1935. Informs the user. Normally on the status bar, optionally
  1936. also on the shell.
  1937. :param msg: Text to write.
  1938. :type msg: str
  1939. :param shell_echo: Control if to display the message msg in the Shell
  1940. :type shell_echo: bool
  1941. :return: None
  1942. """
  1943. # Type of message in brackets at the beginning of the message.
  1944. match = re.search(r"\[(.*)\](.*)", msg)
  1945. if match:
  1946. level = match.group(1)
  1947. msg_ = match.group(2)
  1948. self.ui.fcinfo.set_status(str(msg_), level=level)
  1949. if shell_echo is True:
  1950. if level.lower() == "error":
  1951. self.shell_message(msg, error=True, show=True)
  1952. elif level.lower() == "warning":
  1953. self.shell_message(msg, warning=True, show=True)
  1954. elif level.lower() == "error_notcl":
  1955. self.shell_message(msg, error=True, show=False)
  1956. elif level.lower() == "warning_notcl":
  1957. self.shell_message(msg, warning=True, show=False)
  1958. elif level.lower() == "success":
  1959. self.shell_message(msg, success=True, show=False)
  1960. elif level.lower() == "selected":
  1961. self.shell_message(msg, selected=True, show=False)
  1962. else:
  1963. self.shell_message(msg, show=False)
  1964. else:
  1965. self.ui.fcinfo.set_status(str(msg), level="info")
  1966. # make sure that if the message is to clear the infobar with a space
  1967. # is not printed over and over on the shell
  1968. if msg != '' and shell_echo is True:
  1969. self.shell_message(msg)
  1970. def on_import_preferences(self):
  1971. """
  1972. Loads the application default settings from a saved file into
  1973. ``self.defaults`` dictionary.
  1974. :return: None
  1975. """
  1976. self.defaults.report_usage("on_import_preferences")
  1977. App.log.debug("App.on_import_preferences()")
  1978. # Show file chooser
  1979. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1980. try:
  1981. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1982. directory=self.data_path,
  1983. filter=filter_)
  1984. except TypeError:
  1985. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1986. filter=filter_)
  1987. filename = str(filename)
  1988. if filename == "":
  1989. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1990. return
  1991. # Load in the defaults from the chosen file
  1992. self.defaults.load(filename=filename)
  1993. self.preferencesUiManager.on_preferences_edited()
  1994. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1995. def on_export_preferences(self):
  1996. """
  1997. Save the defaults dictionary to a file.
  1998. :return: None
  1999. """
  2000. self.defaults.report_usage("on_export_preferences")
  2001. App.log.debug("on_export_preferences()")
  2002. # defaults_file_content = None
  2003. # Show file chooser
  2004. date = str(datetime.today()).rpartition('.')[0]
  2005. date = ''.join(c for c in date if c not in ':-')
  2006. date = date.replace(' ', '_')
  2007. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2008. try:
  2009. filename, _f = FCFileSaveDialog.get_saved_filename(
  2010. caption=_("Export FlatCAM Preferences"),
  2011. directory=self.data_path + '/preferences_' + date,
  2012. ext_filter=filter__
  2013. )
  2014. except TypeError:
  2015. filename, _f = FCFileSaveDialog.get_saved_filename(
  2016. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2017. filename = str(filename)
  2018. if filename == "":
  2019. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2020. return
  2021. # Update options
  2022. self.preferencesUiManager.defaults_read_form()
  2023. self.defaults.propagate_defaults()
  2024. # Save update options
  2025. try:
  2026. self.defaults.write(filename=filename)
  2027. except Exception:
  2028. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2029. return
  2030. if self.defaults["global_open_style"] is False:
  2031. self.file_opened.emit("preferences", filename)
  2032. self.file_saved.emit("preferences", filename)
  2033. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2034. def save_to_file(self, content_to_save, txt_content):
  2035. """
  2036. Save something to a file.
  2037. :return: None
  2038. """
  2039. self.defaults.report_usage("save_to_file")
  2040. App.log.debug("save_to_file()")
  2041. self.date = str(datetime.today()).rpartition('.')[0]
  2042. self.date = ''.join(c for c in self.date if c not in ':-')
  2043. self.date = self.date.replace(' ', '_')
  2044. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2045. path_to_save = self.defaults["global_last_save_folder"] if \
  2046. self.defaults["global_last_save_folder"] is not None else self.data_path
  2047. try:
  2048. filename, _f = FCFileSaveDialog.get_saved_filename(
  2049. caption=_("Save to file"),
  2050. directory=path_to_save + '/file_' + self.date,
  2051. ext_filter=filter__
  2052. )
  2053. except TypeError:
  2054. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2055. filename = str(filename)
  2056. if filename == "":
  2057. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2058. return
  2059. else:
  2060. try:
  2061. with open(filename, 'w') as f:
  2062. ___ = f.read()
  2063. except PermissionError:
  2064. self.inform.emit('[WARNING] %s' %
  2065. _("Permission denied, saving not possible.\n"
  2066. "Most likely another app is holding the file open and not accessible."))
  2067. return
  2068. except IOError:
  2069. App.log.debug('Creating a new file ...')
  2070. f = open(filename, 'w')
  2071. f.close()
  2072. except Exception:
  2073. e = sys.exc_info()[0]
  2074. App.log.error("Could not load the file.")
  2075. App.log.error(str(e))
  2076. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2077. return
  2078. # Save content
  2079. if filename.rpartition('.')[2].lower() == 'html':
  2080. file_content = content_to_save
  2081. else:
  2082. file_content = txt_content
  2083. try:
  2084. with open(filename, "w") as f:
  2085. f.write(file_content)
  2086. except Exception:
  2087. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2088. return
  2089. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2090. def register_recent(self, kind, filename):
  2091. """
  2092. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2093. dictionary.
  2094. :param kind: type of file that was opened
  2095. :param filename: the path and file name for the file that was opened
  2096. :return:
  2097. """
  2098. self.log.debug("register_recent()")
  2099. self.log.debug(" %s" % kind)
  2100. self.log.debug(" %s" % filename)
  2101. record = {'kind': str(kind), 'filename': str(filename)}
  2102. if record in self.recent:
  2103. return
  2104. if record in self.recent_projects:
  2105. return
  2106. if record['kind'] == 'project':
  2107. self.recent_projects.insert(0, record)
  2108. else:
  2109. self.recent.insert(0, record)
  2110. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2111. self.recent.pop()
  2112. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2113. self.recent_projects.pop()
  2114. try:
  2115. f = open(self.data_path + '/recent.json', 'w')
  2116. except IOError:
  2117. App.log.error("Failed to open recent items file for writing.")
  2118. self.inform.emit('[ERROR_NOTCL] %s' %
  2119. _('Failed to open recent files file for writing.'))
  2120. return
  2121. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2122. f.close()
  2123. try:
  2124. fp = open(self.data_path + '/recent_projects.json', 'w')
  2125. except IOError:
  2126. App.log.error("Failed to open recent items file for writing.")
  2127. self.inform.emit('[ERROR_NOTCL] %s' %
  2128. _('Failed to open recent projects file for writing.'))
  2129. return
  2130. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2131. fp.close()
  2132. # Re-build the recent items menu
  2133. self.setup_recent_items()
  2134. def on_about(self):
  2135. """
  2136. Displays the "about" dialog found in the Menu --> Help.
  2137. :return: None
  2138. """
  2139. self.defaults.report_usage("on_about")
  2140. version = self.version
  2141. version_date = self.version_date
  2142. beta = self.beta
  2143. class AboutDialog(QtWidgets.QDialog):
  2144. def __init__(self, app, parent=None):
  2145. QtWidgets.QDialog.__init__(self, parent)
  2146. self.app = app
  2147. # Icon and title
  2148. self.setWindowIcon(parent.app_icon)
  2149. self.setWindowTitle(_("About FlatCAM"))
  2150. self.resize(600, 200)
  2151. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2152. # self.setStyleSheet(
  2153. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2154. # "background-attachment: fixed"
  2155. # )
  2156. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2157. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2158. # palette = QtGui.QPalette()
  2159. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2160. # self.setPalette(palette)
  2161. logo = QtWidgets.QLabel()
  2162. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2163. title = QtWidgets.QLabel(
  2164. "<font size=8><B>FlatCAM</B></font><BR>"
  2165. "{title}<BR>"
  2166. "<BR>"
  2167. "<BR>"
  2168. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2169. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2170. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2171. "<B>{issue}</B></a><BR>".format(
  2172. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2173. devel=_("Development"),
  2174. down=_("DOWNLOAD"),
  2175. issue=_("Issue tracker"))
  2176. )
  2177. title.setOpenExternalLinks(True)
  2178. closebtn = QtWidgets.QPushButton(_("Close"))
  2179. tab_widget = QtWidgets.QTabWidget()
  2180. description_label = QtWidgets.QLabel(
  2181. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2182. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2183. version=version,
  2184. beta=('BETA' if beta else ''),
  2185. date=version_date,
  2186. arch=platform.architecture()[0])
  2187. )
  2188. description_label.setOpenExternalLinks(True)
  2189. lic_lbl_header = QtWidgets.QLabel(
  2190. '%s:<br>%s<br>' % (
  2191. _('Licensed under the MIT license'),
  2192. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2193. "http://www.opensource.org/licenses/mit-license.php</a>"
  2194. )
  2195. )
  2196. lic_lbl_header.setOpenExternalLinks(True)
  2197. lic_lbl_body = QtWidgets.QLabel(
  2198. _(
  2199. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2200. 'of this software and associated documentation files (the "Software"), to deal\n'
  2201. 'in the Software without restriction, including without limitation the rights\n'
  2202. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2203. 'copies of the Software, and to permit persons to whom the Software is\n'
  2204. 'furnished to do so, subject to the following conditions:\n\n'
  2205. 'The above copyright notice and this permission notice shall be included in\n'
  2206. 'all copies or substantial portions of the Software.\n\n'
  2207. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2208. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2209. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2210. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2211. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2212. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2213. 'THE SOFTWARE.'
  2214. )
  2215. )
  2216. attributions_label = QtWidgets.QLabel(
  2217. _(
  2218. 'Some of the icons used are from the following sources:<br>'
  2219. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2220. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2221. 'title="Flaticon">www.flaticon.com</a></div>'
  2222. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2223. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2224. )
  2225. )
  2226. attributions_label.setOpenExternalLinks(True)
  2227. # layouts
  2228. layout1 = QtWidgets.QVBoxLayout()
  2229. layout1_1 = QtWidgets.QHBoxLayout()
  2230. layout1_2 = QtWidgets.QHBoxLayout()
  2231. layout2 = QtWidgets.QHBoxLayout()
  2232. layout3 = QtWidgets.QHBoxLayout()
  2233. self.setLayout(layout1)
  2234. layout1.addLayout(layout1_1)
  2235. layout1.addLayout(layout1_2)
  2236. layout1.addLayout(layout2)
  2237. layout1.addLayout(layout3)
  2238. layout1_1.addStretch()
  2239. layout1_1.addWidget(description_label)
  2240. layout1_2.addWidget(tab_widget)
  2241. self.splash_tab = QtWidgets.QWidget()
  2242. self.splash_tab.setObjectName("splash_about")
  2243. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2244. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2245. tab_widget.addTab(self.splash_tab, _("Splash"))
  2246. self.programmmers_tab = QtWidgets.QWidget()
  2247. self.programmmers_tab.setObjectName("programmers_about")
  2248. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2249. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2250. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2251. self.translators_tab = QtWidgets.QWidget()
  2252. self.translators_tab.setObjectName("translators_about")
  2253. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2254. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2255. tab_widget.addTab(self.translators_tab, _("Translators"))
  2256. self.license_tab = QtWidgets.QWidget()
  2257. self.license_tab.setObjectName("license_about")
  2258. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2259. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2260. tab_widget.addTab(self.license_tab, _("License"))
  2261. self.attributions_tab = QtWidgets.QWidget()
  2262. self.attributions_tab.setObjectName("attributions_about")
  2263. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2264. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2265. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2266. self.splash_tab_layout.addWidget(logo, stretch=0)
  2267. self.splash_tab_layout.addWidget(title, stretch=1)
  2268. pal = QtGui.QPalette()
  2269. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2270. self.prog_grid_lay = QtWidgets.QGridLayout()
  2271. self.prog_grid_lay.setHorizontalSpacing(20)
  2272. self.prog_grid_lay.setColumnStretch(0, 0)
  2273. self.prog_grid_lay.setColumnStretch(2, 1)
  2274. prog_widget = QtWidgets.QWidget()
  2275. prog_widget.setLayout(self.prog_grid_lay)
  2276. prog_scroll = QtWidgets.QScrollArea()
  2277. prog_scroll.setWidget(prog_widget)
  2278. prog_scroll.setWidgetResizable(True)
  2279. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2280. prog_scroll.setPalette(pal)
  2281. self.programmmers_tab_layout.addWidget(prog_scroll)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2329. self.translator_grid_lay = QtWidgets.QGridLayout()
  2330. self.translator_grid_lay.setColumnStretch(0, 0)
  2331. self.translator_grid_lay.setColumnStretch(1, 0)
  2332. self.translator_grid_lay.setColumnStretch(2, 1)
  2333. self.translator_grid_lay.setColumnStretch(3, 0)
  2334. # trans_widget = QtWidgets.QWidget()
  2335. # trans_widget.setLayout(self.translator_grid_lay)
  2336. # self.translators_tab_layout.addWidget(trans_widget)
  2337. # self.translators_tab_layout.addStretch()
  2338. trans_widget = QtWidgets.QWidget()
  2339. trans_widget.setLayout(self.translator_grid_lay)
  2340. trans_scroll = QtWidgets.QScrollArea()
  2341. trans_scroll.setWidget(trans_widget)
  2342. trans_scroll.setWidgetResizable(True)
  2343. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2344. trans_scroll.setPalette(pal)
  2345. self.translators_tab_layout.addWidget(trans_scroll)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2365. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2379. self.translator_grid_lay.setColumnStretch(0, 0)
  2380. self.translators_tab_layout.addStretch()
  2381. self.license_tab_layout.addWidget(lic_lbl_header)
  2382. self.license_tab_layout.addWidget(lic_lbl_body)
  2383. self.license_tab_layout.addStretch()
  2384. self.attributions_tab_layout.addWidget(attributions_label)
  2385. self.attributions_tab_layout.addStretch()
  2386. layout3.addStretch()
  2387. layout3.addWidget(closebtn)
  2388. closebtn.clicked.connect(self.accept)
  2389. AboutDialog(app=self, parent=self.ui).exec_()
  2390. def on_readme(self):
  2391. class AboutDialog(QtWidgets.QDialog):
  2392. def __init__(self, app, parent=None):
  2393. QtWidgets.QDialog.__init__(self, parent)
  2394. self.app = app
  2395. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2396. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2397. "<b>new features</b></a>"
  2398. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2399. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2400. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2401. # Icon and title
  2402. self.setWindowIcon(parent.app_icon)
  2403. self.setWindowTitle(_("Important Information's"))
  2404. self.resize(720, 330)
  2405. logo = QtWidgets.QLabel()
  2406. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2407. content = QtWidgets.QLabel(
  2408. "This program is %s and free in a very wide meaning of the word.<br>"
  2409. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2410. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2411. "you can <b>contribute</b> to the development yourself by:<br>"
  2412. "<ul>"
  2413. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2414. "<li>%s by providing the steps required to reproduce the bug</li>"
  2415. "<li>or by making a %s.</li>"
  2416. "</ul>"
  2417. "There are no strings attached.<br>"
  2418. "You don't have to make a %s, and it is totally optional but:"
  2419. "<ul>"
  2420. "<li>it will be welcomed with joy &#128077;</li>"
  2421. "<li>it will give me a reason to continue &#128513;</li>"
  2422. "</ul>" %
  2423. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2424. )
  2425. content.setOpenExternalLinks(True)
  2426. closebtn = QtWidgets.QPushButton(_("Close"))
  2427. # layouts
  2428. layout1 = QtWidgets.QVBoxLayout()
  2429. self.setLayout(layout1)
  2430. pal = QtGui.QPalette()
  2431. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2432. self.grid_lay = QtWidgets.QGridLayout()
  2433. self.grid_lay.setHorizontalSpacing(20)
  2434. self.grid_lay.setColumnStretch(0, 0)
  2435. self.grid_lay.setColumnStretch(1, 1)
  2436. content_widget = QtWidgets.QWidget()
  2437. content_widget.setLayout(self.grid_lay)
  2438. scroll_area = QtWidgets.QScrollArea()
  2439. scroll_area.setWidget(content_widget)
  2440. scroll_area.setWidgetResizable(True)
  2441. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2442. scroll_area.setPalette(pal)
  2443. self.grid_lay.addWidget(logo, 0, 0)
  2444. self.grid_lay.addWidget(content, 0, 1)
  2445. layout1.addWidget(scroll_area)
  2446. layout2 = QtWidgets.QHBoxLayout()
  2447. layout1.addLayout(layout2)
  2448. layout2.addStretch()
  2449. layout2.addWidget(closebtn)
  2450. closebtn.clicked.connect(self.accept)
  2451. AboutDialog(app=self, parent=self.ui).exec_()
  2452. def install_bookmarks(self, book_dict=None):
  2453. """
  2454. Install the bookmarks actions in the Help menu -> Bookmarks
  2455. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2456. :return: None
  2457. """
  2458. if book_dict is None:
  2459. self.defaults["global_bookmarks"].update(
  2460. {
  2461. '1': ['FlatCAM', "http://flatcam.org"],
  2462. '2': ['Backup Site', ""]
  2463. }
  2464. )
  2465. else:
  2466. self.defaults["global_bookmarks"].clear()
  2467. self.defaults["global_bookmarks"].update(book_dict)
  2468. # first try to disconnect if somehow they get connected from elsewhere
  2469. for act in self.ui.menuhelp_bookmarks.actions():
  2470. try:
  2471. act.triggered.disconnect()
  2472. except TypeError:
  2473. pass
  2474. # clear all actions except the last one who is the Bookmark manager
  2475. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2476. pass
  2477. else:
  2478. self.ui.menuhelp_bookmarks.removeAction(act)
  2479. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2480. if self.defaults["global_bookmarks"]:
  2481. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2482. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2483. # the JSON is first making the keys as strings (therefore I have to use strings too
  2484. # or do the conversion :(
  2485. # )
  2486. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2487. # the '10' entry jsut after '1' therefore ordering as strings
  2488. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2489. key=lambda x: int(x[0]))
  2490. for entry, bookmark in sorted_bookmarks:
  2491. title = bookmark[0]
  2492. weblink = bookmark[1]
  2493. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2494. act.setText(title)
  2495. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2496. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2497. if title == 'Backup Site' and weblink == "":
  2498. act.triggered.connect(self.on_backup_site)
  2499. else:
  2500. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2501. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2502. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2503. def on_bookmarks_manager(self):
  2504. """
  2505. Adds the bookmark manager in a Tab in Plot Area
  2506. :return:
  2507. """
  2508. for idx in range(self.ui.plot_tab_area.count()):
  2509. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2510. # there can be only one instance of Bookmark Manager at one time
  2511. return
  2512. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2513. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2514. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2515. # add the tab if it was closed
  2516. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2517. # delete the absolute and relative position and messages in the infobar
  2518. self.ui.position_label.setText("")
  2519. # self.ui.rel_position_label.setText("")
  2520. # Switch plot_area to preferences page
  2521. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2522. def on_backup_site(self):
  2523. msgbox = QtWidgets.QMessageBox()
  2524. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2525. "1. FlatCAM.org website is down\n"
  2526. "2. Someone forked FlatCAM project and wants to point\n"
  2527. "to his own website\n\n"
  2528. "If you can't get any informations about FlatCAM beta\n"
  2529. "use the YouTube channel link from the Help menu."))
  2530. msgbox.setWindowTitle(_("Alternative website"))
  2531. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2532. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2533. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2534. msgbox.setDefaultButton(bt_yes)
  2535. msgbox.exec_()
  2536. # response = msgbox.clickedButton()
  2537. def on_file_savedefaults(self):
  2538. """
  2539. Callback for menu item File->Save Defaults. Saves application default options
  2540. ``self.defaults`` to current_defaults.FlatConfig.
  2541. :return: None
  2542. """
  2543. self.preferencesUiManager.save_defaults()
  2544. def final_save(self):
  2545. """
  2546. Callback for doing a preferences save to file whenever the application is about to quit.
  2547. If the project has changes, it will ask the user to save the project.
  2548. :return: None
  2549. """
  2550. if self.save_in_progress:
  2551. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2552. return
  2553. if self.should_we_save and self.collection.get_list():
  2554. msgbox = QtWidgets.QMessageBox()
  2555. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2556. "\n"
  2557. "Do you want to Save the project?"))
  2558. msgbox.setWindowTitle(_("Save changes"))
  2559. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2560. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2561. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2562. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2563. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2564. msgbox.setDefaultButton(bt_yes)
  2565. msgbox.exec_()
  2566. response = msgbox.clickedButton()
  2567. if response == bt_yes:
  2568. try:
  2569. self.trayIcon.hide()
  2570. except Exception:
  2571. pass
  2572. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2573. elif response == bt_no:
  2574. try:
  2575. self.trayIcon.hide()
  2576. except Exception:
  2577. pass
  2578. self.quit_application()
  2579. elif response == bt_cancel:
  2580. return
  2581. else:
  2582. try:
  2583. self.trayIcon.hide()
  2584. except Exception:
  2585. pass
  2586. self.quit_application()
  2587. def quit_application(self):
  2588. """
  2589. Called (as a pyslot or not) when the application is quit.
  2590. :return: None
  2591. """
  2592. self.preferencesUiManager.save_defaults(silent=True)
  2593. log.debug("App.quit_application() --> App Defaults saved.")
  2594. if self.cmd_line_headless != 1:
  2595. # save app state to file
  2596. stgs = QSettings("Open Source", "FlatCAM")
  2597. stgs.setValue('saved_gui_state', self.ui.saveState())
  2598. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2599. stgs.setValue(
  2600. 'language',
  2601. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2602. )
  2603. stgs.setValue(
  2604. 'notebook_font_size',
  2605. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2606. )
  2607. stgs.setValue(
  2608. 'axis_font_size',
  2609. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2610. )
  2611. stgs.setValue(
  2612. 'textbox_font_size',
  2613. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2614. )
  2615. stgs.setValue(
  2616. 'hud_font_size',
  2617. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2618. )
  2619. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2620. stgs.setValue(
  2621. 'machinist',
  2622. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2623. )
  2624. # This will write the setting to the platform specific storage.
  2625. del stgs
  2626. log.debug("App.quit_application() --> App UI state saved.")
  2627. # try to quit the Socket opened by ArgsThread class
  2628. try:
  2629. self.new_launch.stop.emit()
  2630. except Exception as err:
  2631. log.debug("App.quit_application() --> %s" % str(err))
  2632. # try to quit the QThread that run ArgsThread class
  2633. try:
  2634. self.th.quit()
  2635. except Exception as e:
  2636. log.debug("App.quit_application() --> %s" % str(e))
  2637. # terminate workers
  2638. self.workers.__del__()
  2639. # quit app by signalling for self.kill_app() method
  2640. # self.close_app_signal.emit()
  2641. QtWidgets.qApp.quit()
  2642. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2643. # we use the following command
  2644. minor_v = sys.version_info.minor
  2645. if minor_v < 8:
  2646. sys.exit(0)
  2647. else:
  2648. os._exit(0) # fix to work with Python 3.8
  2649. @staticmethod
  2650. def kill_app():
  2651. QtWidgets.qApp.quit()
  2652. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2653. # we use the following command
  2654. sys.exit(0)
  2655. def on_portable_checked(self, state):
  2656. """
  2657. Callback called when the checkbox in Preferences GUI is checked.
  2658. It will set the application as portable by creating the preferences and recent files in the
  2659. 'config' folder found in the FlatCAM installation folder.
  2660. :param state: boolean, the state of the checkbox when clicked/checked
  2661. :return:
  2662. """
  2663. line_no = 0
  2664. data = None
  2665. if sys.platform != 'win32':
  2666. # this won't work in Linux or MacOS
  2667. return
  2668. # test if the app was frozen and choose the path for the configuration file
  2669. if getattr(sys, "frozen", False) is True:
  2670. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2671. else:
  2672. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2673. config_file = current_data_path + '\\configuration.txt'
  2674. try:
  2675. with open(config_file, 'r') as f:
  2676. try:
  2677. data = f.readlines()
  2678. except Exception as e:
  2679. log.debug('App.__init__() -->%s' % str(e))
  2680. return
  2681. except FileNotFoundError:
  2682. pass
  2683. for line in data:
  2684. line = line.strip('\n')
  2685. param = str(line).rpartition('=')
  2686. if param[0] == 'portable':
  2687. break
  2688. line_no += 1
  2689. if state:
  2690. data[line_no] = 'portable=True\n'
  2691. # create the new defauults files
  2692. # create current_defaults.FlatConfig file if there is none
  2693. try:
  2694. f = open(current_data_path + '/current_defaults.FlatConfig')
  2695. f.close()
  2696. except IOError:
  2697. App.log.debug('Creating empty current_defaults.FlatConfig')
  2698. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2699. json.dump({}, f)
  2700. f.close()
  2701. # create factory_defaults.FlatConfig file if there is none
  2702. try:
  2703. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2704. f.close()
  2705. except IOError:
  2706. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2707. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2708. json.dump({}, f)
  2709. f.close()
  2710. try:
  2711. f = open(current_data_path + '/recent.json')
  2712. f.close()
  2713. except IOError:
  2714. App.log.debug('Creating empty recent.json')
  2715. f = open(current_data_path + '/recent.json', 'w')
  2716. json.dump([], f)
  2717. f.close()
  2718. try:
  2719. fp = open(current_data_path + '/recent_projects.json')
  2720. fp.close()
  2721. except IOError:
  2722. App.log.debug('Creating empty recent_projects.json')
  2723. fp = open(current_data_path + '/recent_projects.json', 'w')
  2724. json.dump([], fp)
  2725. fp.close()
  2726. # save the current defaults to the new defaults file
  2727. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2728. else:
  2729. data[line_no] = 'portable=False\n'
  2730. with open(config_file, 'w') as f:
  2731. f.writelines(data)
  2732. def on_register_files(self, obj_type=None):
  2733. """
  2734. Called whenever there is a need to register file extensions with FlatCAM.
  2735. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2736. :param obj_type: the type of object to be register for.
  2737. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2738. :return: None
  2739. """
  2740. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2741. new_reg_path = 'Software\\Classes\\'
  2742. # find if the current user is admin
  2743. try:
  2744. is_admin = os.getuid() == 0
  2745. except AttributeError:
  2746. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2747. if is_admin is True:
  2748. root_path = winreg.HKEY_LOCAL_MACHINE
  2749. else:
  2750. root_path = winreg.HKEY_CURRENT_USER
  2751. # create the keys
  2752. def set_reg(name, root_pth, new_reg_path, value):
  2753. try:
  2754. winreg.CreateKey(root_pth, new_reg_path)
  2755. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2756. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2757. return True
  2758. except WindowsError:
  2759. return False
  2760. # delete key in registry
  2761. def delete_reg(root_pth, reg_path, key_to_del):
  2762. key_to_del_path = reg_path + key_to_del
  2763. try:
  2764. winreg.DeleteKey(root_pth, key_to_del_path)
  2765. return True
  2766. except WindowsError:
  2767. return False
  2768. if obj_type is None or obj_type == 'excellon':
  2769. exc_list = \
  2770. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2771. exc_list = [x for x in exc_list if x != '']
  2772. # register all keys in the Preferences window
  2773. for ext in exc_list:
  2774. new_k = new_reg_path + '.%s' % ext
  2775. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2776. # and unregister those that are no longer in the Preferences windows but are in the file
  2777. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2778. if ext not in exc_list:
  2779. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2780. # now write the updated extensions to the self.defaults
  2781. # new_ext = ''
  2782. # for ext in exc_list:
  2783. # new_ext = new_ext + ext + ', '
  2784. # self.defaults["fa_excellon"] = new_ext
  2785. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2786. if obj_type is None or obj_type == 'gcode':
  2787. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2788. gco_list = [x for x in gco_list if x != '']
  2789. # register all keys in the Preferences window
  2790. for ext in gco_list:
  2791. new_k = new_reg_path + '.%s' % ext
  2792. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2793. # and unregister those that are no longer in the Preferences windows but are in the file
  2794. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2795. if ext not in gco_list:
  2796. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2797. # now write the updated extensions to the self.defaults
  2798. # new_ext = ''
  2799. # for ext in gco_list:
  2800. # new_ext = new_ext + ext + ', '
  2801. # self.defaults["fa_gcode"] = new_ext
  2802. self.inform.emit('[success] %s' %
  2803. _("Selected GCode file extensions registered with FlatCAM."))
  2804. if obj_type is None or obj_type == 'gerber':
  2805. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2806. grb_list = [x for x in grb_list if x != '']
  2807. # register all keys in the Preferences window
  2808. for ext in grb_list:
  2809. new_k = new_reg_path + '.%s' % ext
  2810. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2811. # and unregister those that are no longer in the Preferences windows but are in the file
  2812. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2813. if ext not in grb_list:
  2814. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2815. # now write the updated extensions to the self.defaults
  2816. # new_ext = ''
  2817. # for ext in grb_list:
  2818. # new_ext = new_ext + ext + ', '
  2819. # self.defaults["fa_gerber"] = new_ext
  2820. self.inform.emit('[success] %s' %
  2821. _("Selected Gerber file extensions registered with FlatCAM."))
  2822. def add_extension(self, ext_type):
  2823. """
  2824. Add a file extension to the list for a specific object
  2825. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2826. :return:
  2827. """
  2828. if ext_type == 'excellon':
  2829. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2830. if new_ext == '':
  2831. return
  2832. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2833. if new_ext in old_val:
  2834. return
  2835. old_val.append(new_ext)
  2836. old_val.sort()
  2837. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2838. if ext_type == 'gcode':
  2839. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2840. if new_ext == '':
  2841. return
  2842. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2843. if new_ext in old_val:
  2844. return
  2845. old_val.append(new_ext)
  2846. old_val.sort()
  2847. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2848. if ext_type == 'gerber':
  2849. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2850. if new_ext == '':
  2851. return
  2852. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2853. if new_ext in old_val:
  2854. return
  2855. old_val.append(new_ext)
  2856. old_val.sort()
  2857. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2858. if ext_type == 'keyword':
  2859. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2860. if new_kw == '':
  2861. return
  2862. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2863. if new_kw in old_val:
  2864. return
  2865. old_val.append(new_kw)
  2866. old_val.sort()
  2867. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2868. # update the self.myKeywords so the model is updated
  2869. self.autocomplete_kw_list = \
  2870. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2871. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2872. self.shell._edit.set_model_data(self.myKeywords)
  2873. def del_extension(self, ext_type):
  2874. """
  2875. Remove a file extension from the list for a specific object
  2876. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2877. :return:
  2878. """
  2879. if ext_type == 'excellon':
  2880. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2881. if new_ext == '':
  2882. return
  2883. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2884. if new_ext not in old_val:
  2885. return
  2886. old_val.remove(new_ext)
  2887. old_val.sort()
  2888. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2889. if ext_type == 'gcode':
  2890. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2891. if new_ext == '':
  2892. return
  2893. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2894. if new_ext not in old_val:
  2895. return
  2896. old_val.remove(new_ext)
  2897. old_val.sort()
  2898. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2899. if ext_type == 'gerber':
  2900. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2901. if new_ext == '':
  2902. return
  2903. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2904. if new_ext not in old_val:
  2905. return
  2906. old_val.remove(new_ext)
  2907. old_val.sort()
  2908. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2909. if ext_type == 'keyword':
  2910. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2911. if new_kw == '':
  2912. return
  2913. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2914. if new_kw not in old_val:
  2915. return
  2916. old_val.remove(new_kw)
  2917. old_val.sort()
  2918. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2919. # update the self.myKeywords so the model is updated
  2920. self.autocomplete_kw_list = \
  2921. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2922. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2923. self.shell._edit.set_model_data(self.myKeywords)
  2924. def restore_extensions(self, ext_type):
  2925. """
  2926. Restore all file extensions associations with FlatCAM, for a specific object
  2927. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2928. :return:
  2929. """
  2930. if ext_type == 'excellon':
  2931. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2932. # for the ability to open Excellon files with .txt extension
  2933. new_exc_list = deepcopy(self.exc_list)
  2934. try:
  2935. new_exc_list.remove('txt')
  2936. except ValueError:
  2937. pass
  2938. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2939. if ext_type == 'gcode':
  2940. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2941. if ext_type == 'gerber':
  2942. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2943. if ext_type == 'keyword':
  2944. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2945. # update the self.myKeywords so the model is updated
  2946. self.autocomplete_kw_list = self.default_keywords
  2947. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2948. self.shell._edit.set_model_data(self.myKeywords)
  2949. def delete_all_extensions(self, ext_type):
  2950. """
  2951. Delete all file extensions associations with FlatCAM, for a specific object
  2952. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2953. :return:
  2954. """
  2955. if ext_type == 'excellon':
  2956. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2957. if ext_type == 'gcode':
  2958. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2959. if ext_type == 'gerber':
  2960. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2961. if ext_type == 'keyword':
  2962. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2963. # update the self.myKeywords so the model is updated
  2964. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2965. self.shell._edit.set_model_data(self.myKeywords)
  2966. def on_edit_join(self, name=None):
  2967. """
  2968. Callback for Edit->Join. Joins the selected geometry objects into
  2969. a new one.
  2970. :return: None
  2971. """
  2972. self.defaults.report_usage("on_edit_join()")
  2973. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2974. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2975. geo_type_set = set()
  2976. objs = self.collection.get_selected()
  2977. if len(objs) < 2:
  2978. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2979. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2980. return 'fail'
  2981. for obj in objs:
  2982. geo_type_set.add(obj.multigeo)
  2983. # if len(geo_type_list) == 1 means that all list elements are the same
  2984. if len(geo_type_set) != 1:
  2985. self.inform.emit('[ERROR] %s' %
  2986. _("Failed join. The Geometry objects are of different types.\n"
  2987. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2988. "convert from one to another and retry joining \n"
  2989. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2990. "the result may not be what was expected. \n"
  2991. "Check the generated GCODE."))
  2992. return
  2993. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2994. if True in geo_type_set:
  2995. def initialize(geo_obj, app):
  2996. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2997. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2998. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2999. for v in geo_obj.tools.values():
  3000. v['data']['name'] = obj_name_multi
  3001. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3002. else:
  3003. def initialize(geo_obj, app):
  3004. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3005. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3006. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3007. for v in geo_obj.tools.values():
  3008. v['data']['name'] = obj_name_single
  3009. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3010. self.should_we_save = True
  3011. def on_edit_join_exc(self):
  3012. """
  3013. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3014. a new Excellon.
  3015. :return: None
  3016. """
  3017. self.defaults.report_usage("on_edit_join_exc()")
  3018. objs = self.collection.get_selected()
  3019. for obj in objs:
  3020. if not isinstance(obj, ExcellonObject):
  3021. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3022. return
  3023. if len(objs) < 2:
  3024. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3025. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3026. return 'fail'
  3027. def initialize(exc_obj, app):
  3028. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3029. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3030. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3031. self.should_we_save = True
  3032. def on_edit_join_grb(self):
  3033. """
  3034. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3035. a new Gerber object.
  3036. :return: None
  3037. """
  3038. self.defaults.report_usage("on_edit_join_grb()")
  3039. objs = self.collection.get_selected()
  3040. for obj in objs:
  3041. if not isinstance(obj, GerberObject):
  3042. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3043. return
  3044. if len(objs) < 2:
  3045. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3046. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3047. return 'fail'
  3048. def initialize(grb_obj, app):
  3049. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3050. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3051. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3052. self.should_we_save = True
  3053. def on_convert_singlegeo_to_multigeo(self):
  3054. """
  3055. Called for converting a Geometry object from single-geo to multi-geo.
  3056. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3057. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3058. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3059. the solid-geometry of that tool.
  3060. :return: None
  3061. """
  3062. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3063. obj = self.collection.get_active()
  3064. if obj is None:
  3065. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3066. return
  3067. if not isinstance(obj, GeometryObject):
  3068. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3069. return
  3070. obj.multigeo = True
  3071. for tooluid, dict_value in obj.tools.items():
  3072. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3073. if not isinstance(obj.solid_geometry, list):
  3074. obj.solid_geometry = [obj.solid_geometry]
  3075. # obj.solid_geometry[:] = []
  3076. obj.plot()
  3077. self.should_we_save = True
  3078. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3079. def on_convert_multigeo_to_singlegeo(self):
  3080. """
  3081. Called for converting a Geometry object from multi-geo to single-geo.
  3082. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3083. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3084. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3085. the solid-geometry of that tool.
  3086. :return: None
  3087. """
  3088. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3089. obj = self.collection.get_active()
  3090. if obj is None:
  3091. self.inform.emit('[ERROR_NOTCL] %s' %
  3092. _("Failed. Select a Geometry Object and try again."))
  3093. return
  3094. if not isinstance(obj, GeometryObject):
  3095. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3096. (_("Expected a GeometryObject, got"), type(obj)))
  3097. return
  3098. obj.multigeo = False
  3099. total_solid_geometry = []
  3100. for tooluid, dict_value in obj.tools.items():
  3101. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3102. # clear the original geometry
  3103. dict_value['solid_geometry'][:] = []
  3104. obj.solid_geometry = deepcopy(total_solid_geometry)
  3105. obj.plot()
  3106. self.should_we_save = True
  3107. self.inform.emit('[success] %s' %
  3108. _("A Geometry object was converted to SingleGeo type."))
  3109. def on_defaults_dict_change(self, field):
  3110. """
  3111. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3112. Edit -> Preferences tab window.
  3113. :param field: the key of the self.defaults dictionary that was changed.
  3114. :return: None
  3115. """
  3116. self.preferencesUiManager.defaults_write_form_field(field=field)
  3117. if field == "units":
  3118. self.set_screen_units(self.defaults['units'])
  3119. def set_screen_units(self, units):
  3120. """
  3121. Set the FlatCAM units on the status bar.
  3122. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3123. :return: None
  3124. """
  3125. self.ui.units_label.setText("[" + units.lower() + "]")
  3126. def on_toggle_units_click(self):
  3127. try:
  3128. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3129. except (TypeError, AttributeError):
  3130. pass
  3131. if self.defaults["units"] == 'MM':
  3132. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3133. else:
  3134. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3135. self.on_toggle_units(no_pref=True)
  3136. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3137. lambda: self.on_toggle_units(no_pref=False))
  3138. def on_toggle_units(self, no_pref=False):
  3139. """
  3140. Callback for the Units radio-button change in the Preferences tab.
  3141. Changes the application's default units adn for the project too.
  3142. If changing the project's units, the change propagates to all of
  3143. the objects in the project.
  3144. :return: None
  3145. """
  3146. self.defaults.report_usage("on_toggle_units")
  3147. if self.toggle_units_ignore:
  3148. return
  3149. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3150. # If option is the same, then ignore
  3151. if new_units == self.defaults["units"].upper():
  3152. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3153. return
  3154. # Keys in self.defaults for which to scale their values
  3155. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3156. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3157. "tools_iso_tool_vtipdia",
  3158. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3159. "gerber_editor_ma_high",
  3160. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3161. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3162. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3163. "excellon_feedrate_probe", "excellon_milling_dia",
  3164. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3165. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3166. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3167. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3168. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3169. "geometry_extracut_length", "geometry_z_pdepth",
  3170. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3171. 'cncjob_tooldia',
  3172. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3173. "tools_paintnewdia",
  3174. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3175. "tools_nccnewdia", "tools_ncc_offset_value",
  3176. "tools_2sided_drilldia",
  3177. "tools_film_boundary", "tools_film_scale_stroke",
  3178. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3179. "tools_cutout_depthperpass",
  3180. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3181. "tools_panelize_spacing_rows",
  3182. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3183. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3184. "tools_transform_buffer_dis",
  3185. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3186. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3187. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3188. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3189. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3190. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3191. "tools_cr_h2h_val", "tools_cr_dh_val",
  3192. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3193. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3194. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3195. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3196. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3197. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3198. "tools_copper_thieving_mask_clearance",
  3199. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3200. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3201. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3202. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3203. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3204. "tools_invert_margin",
  3205. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3206. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3207. def scale_defaults(sfactor):
  3208. for dim in dimensions:
  3209. if dim in [
  3210. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3211. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3212. 'tools_transform_mirror_point'
  3213. ]:
  3214. if self.defaults[dim] is None or self.defaults[dim] == '':
  3215. continue
  3216. try:
  3217. coordinates = self.defaults[dim].split(",")
  3218. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3219. coords_xy[0] *= sfactor
  3220. coords_xy[1] *= sfactor
  3221. self.defaults[dim] = "%.*f, %.*f" % (
  3222. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3223. except Exception as e:
  3224. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3225. elif dim in [
  3226. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3227. ]:
  3228. if self.defaults[dim] is None or self.defaults[dim] == '':
  3229. continue
  3230. try:
  3231. self.defaults[dim] = float(self.defaults[dim])
  3232. tools_diameters = [self.defaults[dim]]
  3233. except ValueError:
  3234. try:
  3235. tools_string = self.defaults[dim].split(",")
  3236. tools_diameters = [eval(a) for a in tools_string if a != '']
  3237. except Exception as e:
  3238. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3239. continue
  3240. self.defaults[dim] = ''
  3241. td_len = len(tools_diameters)
  3242. if td_len > 1:
  3243. for t in range(td_len):
  3244. tools_diameters[t] *= sfactor
  3245. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3246. else:
  3247. tools_diameters[0] *= sfactor
  3248. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3249. elif dim in ['global_gridx', 'global_gridy']:
  3250. # format the number of decimals to the one specified in self.decimals
  3251. try:
  3252. val = float(self.defaults[dim]) * sfactor
  3253. except Exception as e:
  3254. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3255. continue
  3256. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3257. else:
  3258. # the number of decimals for the rest is kept unchanged
  3259. if self.defaults[dim]:
  3260. try:
  3261. val = float(self.defaults[dim]) * sfactor
  3262. except Exception as e:
  3263. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3264. continue
  3265. self.defaults[dim] = val
  3266. # The scaling factor depending on choice of units.
  3267. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3268. # Changing project units. Warn user.
  3269. msgbox = QtWidgets.QMessageBox()
  3270. msgbox.setWindowTitle(_("Toggle Units"))
  3271. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3272. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3273. msgbox.setText(_("Changing the units of the project\n"
  3274. "will scale all objects.\n\n"
  3275. "Do you want to continue?"))
  3276. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3277. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3278. msgbox.setDefaultButton(bt_ok)
  3279. msgbox.exec_()
  3280. response = msgbox.clickedButton()
  3281. if response == bt_ok:
  3282. if no_pref is False:
  3283. self.preferencesUiManager.defaults_read_form()
  3284. scale_defaults(factor)
  3285. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3286. self.defaults["units"] = new_units
  3287. # update the defaults from form, some may assume that the conversion is enough and it's not
  3288. self.on_options_app2project()
  3289. # update the objects
  3290. for obj in self.collection.get_list():
  3291. obj.convert_units(new_units)
  3292. # make that the properties stored in the object are also updated
  3293. self.app_obj.object_changed.emit(obj)
  3294. # rebuild the object UI
  3295. obj.build_ui()
  3296. # change this only if the workspace is active
  3297. if self.defaults['global_workspace'] is True:
  3298. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3299. # adjust the grid values on the main toolbar
  3300. val_x = float(self.defaults['global_gridx']) * factor
  3301. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3302. current = self.collection.get_active()
  3303. if current is not None:
  3304. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3305. if not isinstance(current, GeometryObject):
  3306. current.to_form()
  3307. # replot all objects
  3308. self.plot_all()
  3309. # set the status labels to reflect the current FlatCAM units
  3310. self.set_screen_units(new_units)
  3311. # signal to the app that we changed the object properties and it should save the project
  3312. self.should_we_save = True
  3313. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3314. else:
  3315. # Undo toggling
  3316. self.toggle_units_ignore = True
  3317. if self.defaults['units'].upper() == 'MM':
  3318. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3319. else:
  3320. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3321. self.toggle_units_ignore = False
  3322. # store the grid values so they are not changed in the next step
  3323. val_x = float(self.defaults['global_gridx'])
  3324. val_y = float(self.defaults['global_gridy'])
  3325. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3326. self.preferencesUiManager.defaults_read_form()
  3327. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3328. # in self.defaults from the GUI elements but
  3329. # I don't want it for the grid values, so I update them here
  3330. self.defaults['global_gridx'] = val_x
  3331. self.defaults['global_gridy'] = val_y
  3332. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3333. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3334. def on_tab_rmb_click(self, checked):
  3335. self.ui.notebook.set_detachable(val=checked)
  3336. self.defaults["global_tabs_detachable"] = checked
  3337. self.ui.plot_tab_area.set_detachable(val=checked)
  3338. self.defaults["global_tabs_detachable"] = checked
  3339. def on_tab_setup_context_menu(self):
  3340. initial_checked = self.defaults["global_tabs_detachable"]
  3341. action_name = str(_("Detachable Tabs"))
  3342. action = QtWidgets.QAction(self)
  3343. action.setCheckable(True)
  3344. action.setText(action_name)
  3345. action.setChecked(initial_checked)
  3346. self.ui.notebook.tabBar.addAction(action)
  3347. self.ui.plot_tab_area.tabBar.addAction(action)
  3348. try:
  3349. action.triggered.disconnect()
  3350. except TypeError:
  3351. pass
  3352. action.triggered.connect(self.on_tab_rmb_click)
  3353. def on_deselect_all(self):
  3354. self.collection.set_all_inactive()
  3355. self.delete_selection_shape()
  3356. def on_workspace_modified(self):
  3357. # self.save_defaults(silent=True)
  3358. self.plotcanvas.delete_workspace()
  3359. self.preferencesUiManager.defaults_read_form()
  3360. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3361. def on_workspace(self):
  3362. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3363. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3364. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3365. else:
  3366. self.plotcanvas.delete_workspace()
  3367. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3368. self.preferencesUiManager.defaults_read_form()
  3369. # self.save_defaults(silent=True)
  3370. def on_workspace_toggle(self):
  3371. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3372. try:
  3373. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3374. except TypeError:
  3375. pass
  3376. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3377. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3378. self.on_workspace()
  3379. def on_cursor_type(self, val):
  3380. """
  3381. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3382. :return: None
  3383. """
  3384. self.app_cursor.enabled = False
  3385. if val == 'small':
  3386. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3387. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3388. self.app_cursor = self.plotcanvas.new_cursor()
  3389. else:
  3390. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3391. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3392. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3393. if self.ui.grid_snap_btn.isChecked():
  3394. self.app_cursor.enabled = True
  3395. else:
  3396. self.app_cursor.enabled = False
  3397. def on_tool_add_keypress(self):
  3398. # ## Current application units in Upper Case
  3399. self.units = self.defaults['units'].upper()
  3400. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3401. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3402. if notebook_widget_name == 'selected_tab':
  3403. if self.collection.get_active().kind == 'geometry':
  3404. # Tool add works for Geometry only if Advanced is True in Preferences
  3405. if self.defaults["global_app_level"] == 'a':
  3406. tool_add_popup = FCInputDialog(title="New Tool ...",
  3407. text='Enter a Tool Diameter:',
  3408. min=0.0000, max=99.9999, decimals=4)
  3409. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3410. val, ok = tool_add_popup.get_value()
  3411. if ok:
  3412. if float(val) == 0:
  3413. self.inform.emit('[WARNING_NOTCL] %s' %
  3414. _("Please enter a tool diameter with non-zero value, in Float format."))
  3415. return
  3416. self.collection.get_active().on_tool_add(dia=float(val))
  3417. else:
  3418. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3419. else:
  3420. msgbox = QtWidgets.QMessageBox()
  3421. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3422. "Go to Preferences -> General - Show Advanced Options."))
  3423. msgbox.setWindowTitle("Tool adding ...")
  3424. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3425. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3426. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3427. msgbox.setDefaultButton(bt_ok)
  3428. msgbox.exec_()
  3429. # work only if the notebook tab on focus is the Tools_Tab
  3430. if notebook_widget_name == 'tool_tab':
  3431. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3432. # and only if the tool is NCC Tool
  3433. if tool_widget == self.ncclear_tool.toolName:
  3434. self.ncclear_tool.on_add_tool_by_key()
  3435. # and only if the tool is Paint Area Tool
  3436. elif tool_widget == self.paint_tool.toolName:
  3437. self.paint_tool.on_add_tool_by_key()
  3438. # and only if the tool is Solder Paste Dispensing Tool
  3439. elif tool_widget == self.paste_tool.toolName:
  3440. self.paste_tool.on_add_tool_by_key()
  3441. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3442. # See description below.
  3443. def on_delete_keypress(self):
  3444. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3445. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3446. if notebook_widget_name == 'selected_tab':
  3447. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3448. self.collection.get_active().on_tool_delete()
  3449. # work only if the notebook tab on focus is the Tools_Tab
  3450. elif notebook_widget_name == 'tool_tab':
  3451. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3452. # and only if the tool is NCC Tool
  3453. if tool_widget == self.ncclear_tool.toolName:
  3454. self.ncclear_tool.on_tool_delete()
  3455. # and only if the tool is Paint Tool
  3456. elif tool_widget == self.paint_tool.toolName:
  3457. self.paint_tool.on_tool_delete()
  3458. # and only if the tool is Solder Paste Dispensing Tool
  3459. elif tool_widget == self.paste_tool.toolName:
  3460. self.paste_tool.on_tool_delete()
  3461. # and only if the tool is Isolation Tool
  3462. elif tool_widget == self.isolation_tool.toolName:
  3463. self.isolation_tool.on_tool_delete()
  3464. else:
  3465. self.on_delete()
  3466. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3467. # some screens you have to be careful where you hover with your mouse.
  3468. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3469. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3470. # Complicated, I know :)
  3471. def on_delete(self, force_deletion=False):
  3472. """
  3473. Delete the currently selected FlatCAMObjs.
  3474. :param force_deletion: used by Tcl command
  3475. :return: None
  3476. """
  3477. self.defaults.report_usage("on_delete()")
  3478. response = None
  3479. bt_ok = None
  3480. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3481. # a geometry object before we update it.
  3482. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3483. and self.grb_editor.editor_active is False:
  3484. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3485. msgbox = QtWidgets.QMessageBox()
  3486. msgbox.setWindowTitle(_("Delete objects"))
  3487. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3488. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3489. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3490. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3491. "the selected objects?"))
  3492. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3493. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3494. msgbox.setDefaultButton(bt_ok)
  3495. msgbox.exec_()
  3496. response = msgbox.clickedButton()
  3497. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3498. response = bt_ok
  3499. if response == bt_ok:
  3500. if self.collection.get_active():
  3501. self.log.debug("App.on_delete()")
  3502. for obj_active in self.collection.get_selected():
  3503. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3504. if obj_active.kind == 'gerber':
  3505. for el in obj_active.mark_shapes:
  3506. obj_active.mark_shapes[el].clear(update=True)
  3507. obj_active.mark_shapes[el].enabled = False
  3508. # obj_active.mark_shapes[el] = None
  3509. del el
  3510. elif obj_active.kind == 'cncjob':
  3511. try:
  3512. obj_active.text_col.enabled = False
  3513. del obj_active.text_col
  3514. obj_active.annotation.clear(update=True)
  3515. del obj_active.annotation
  3516. except AttributeError as e:
  3517. log.debug(
  3518. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3519. )
  3520. while self.collection.get_selected():
  3521. self.delete_first_selected()
  3522. # make sure that the selection shape is deleted, too
  3523. self.delete_selection_shape()
  3524. # if there are no longer objects delete also the exclusion areas shapes
  3525. if not self.collection.get_list():
  3526. self.exc_areas.clear_shapes()
  3527. self.inform.emit('%s...' % _("Object(s) deleted"))
  3528. else:
  3529. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3530. else:
  3531. self.inform.emit(_("Save the work in Editor and try again ..."))
  3532. def delete_first_selected(self):
  3533. # Keep this for later
  3534. try:
  3535. sel_obj = self.collection.get_active()
  3536. name = sel_obj.options["name"]
  3537. isPlotted = sel_obj.options["plot"]
  3538. except AttributeError:
  3539. self.log.debug("Nothing selected for deletion")
  3540. return
  3541. if self.is_legacy is True:
  3542. # Remove plot only if the object was plotted otherwise delaxes will fail
  3543. if isPlotted:
  3544. try:
  3545. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3546. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3547. except Exception as e:
  3548. log.debug("App.delete_first_selected() --> %s" % str(e))
  3549. self.plotcanvas.auto_adjust_axes()
  3550. # Remove from dictionary
  3551. self.collection.delete_active()
  3552. # Clear form
  3553. self.setup_component_editor()
  3554. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3555. def on_set_origin(self):
  3556. """
  3557. Set the origin to the left mouse click position
  3558. :return: None
  3559. """
  3560. # display the message for the user
  3561. # and ask him to click on the desired position
  3562. self.defaults.report_usage("on_set_origin()")
  3563. def origin_replot():
  3564. def worker_task():
  3565. with self.proc_container.new('%s...' % _("Plotting")):
  3566. for obj in self.collection.get_list():
  3567. obj.plot()
  3568. self.plotcanvas.fit_view()
  3569. if self.is_legacy:
  3570. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3571. else:
  3572. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3573. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3574. self.inform.emit(_('Click to set the origin ...'))
  3575. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3576. # first disconnect it as it may have been used by something else
  3577. try:
  3578. self.replot_signal.disconnect()
  3579. except TypeError:
  3580. pass
  3581. self.replot_signal[list].connect(origin_replot)
  3582. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3583. """
  3584. :param event:
  3585. :param location:
  3586. :param noplot:
  3587. :param use_thread:
  3588. :return:
  3589. """
  3590. noplot_sig = noplot
  3591. def worker_task():
  3592. with self.proc_container.new(_("Setting Origin...")):
  3593. obj_list = self.collection.get_list()
  3594. for obj in obj_list:
  3595. obj.offset((x, y))
  3596. self.app_obj.object_changed.emit(obj)
  3597. # Update the object bounding box options
  3598. a, b, c, d = obj.bounds()
  3599. obj.options['xmin'] = a
  3600. obj.options['ymin'] = b
  3601. obj.options['xmax'] = c
  3602. obj.options['ymax'] = d
  3603. self.inform.emit('[success] %s...' % _('Origin set'))
  3604. for obj in obj_list:
  3605. out_name = obj.options["name"]
  3606. if obj.kind == 'gerber':
  3607. obj.source_file = self.export_gerber(
  3608. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3609. elif obj.kind == 'excellon':
  3610. obj.source_file = self.export_excellon(
  3611. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3612. if noplot_sig is False:
  3613. self.replot_signal.emit([])
  3614. if location is not None:
  3615. if len(location) != 2:
  3616. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3617. return 'fail'
  3618. x, y = location
  3619. if use_thread is True:
  3620. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3621. else:
  3622. worker_task()
  3623. self.should_we_save = True
  3624. return
  3625. if event is not None and event.button == 1:
  3626. if self.is_legacy is False:
  3627. event_pos = event.pos
  3628. else:
  3629. event_pos = (event.xdata, event.ydata)
  3630. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3631. if self.grid_status():
  3632. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3633. else:
  3634. pos = pos_canvas
  3635. x = 0 - pos[0]
  3636. y = 0 - pos[1]
  3637. if use_thread is True:
  3638. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3639. else:
  3640. worker_task()
  3641. self.should_we_save = True
  3642. def on_move2origin(self, use_thread=True):
  3643. """
  3644. Move selected objects to origin.
  3645. :param use_thread: Control if to use threaded operation. Boolean.
  3646. :return:
  3647. """
  3648. def worker_task():
  3649. with self.proc_container.new(_("Moving to Origin...")):
  3650. obj_list = self.collection.get_selected()
  3651. if not obj_list:
  3652. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3653. return
  3654. xminlist = []
  3655. yminlist = []
  3656. # first get a bounding box to fit all
  3657. for obj in obj_list:
  3658. xmin, ymin, xmax, ymax = obj.bounds()
  3659. xminlist.append(xmin)
  3660. yminlist.append(ymin)
  3661. # get the minimum x,y for all objects selected
  3662. x = min(xminlist)
  3663. y = min(yminlist)
  3664. for obj in obj_list:
  3665. obj.offset((-x, -y))
  3666. self.app_obj.object_changed.emit(obj)
  3667. # Update the object bounding box options
  3668. a, b, c, d = obj.bounds()
  3669. obj.options['xmin'] = a
  3670. obj.options['ymin'] = b
  3671. obj.options['xmax'] = c
  3672. obj.options['ymax'] = d
  3673. for obj in obj_list:
  3674. obj.plot()
  3675. for obj in obj_list:
  3676. out_name = obj.options["name"]
  3677. if obj.kind == 'gerber':
  3678. obj.source_file = self.export_gerber(
  3679. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3680. elif obj.kind == 'excellon':
  3681. obj.source_file = self.export_excellon(
  3682. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3683. self.inform.emit('[success] %s...' % _('Origin set'))
  3684. if use_thread is True:
  3685. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3686. else:
  3687. worker_task()
  3688. self.should_we_save = True
  3689. def on_jump_to(self, custom_location=None, fit_center=True):
  3690. """
  3691. Jump to a location by setting the mouse cursor location.
  3692. :param custom_location: Jump to a specified point. (x, y) tuple.
  3693. :param fit_center: If to fit view. Boolean.
  3694. :return:
  3695. """
  3696. self.defaults.report_usage("on_jump_to()")
  3697. if not custom_location:
  3698. dia_box_location = None
  3699. try:
  3700. dia_box_location = eval(self.clipboard.text())
  3701. except Exception:
  3702. pass
  3703. if type(dia_box_location) == tuple:
  3704. dia_box_location = str(dia_box_location)
  3705. else:
  3706. dia_box_location = None
  3707. # dia_box = Dialog_box(title=_("Jump to ..."),
  3708. # label=_("Enter the coordinates in format X,Y:"),
  3709. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3710. # initial_text=dia_box_location)
  3711. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3712. label=_("Enter the coordinates in format X,Y:"),
  3713. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3714. initial_text=dia_box_location,
  3715. reference=self.defaults['global_jump_ref'])
  3716. if dia_box.ok is True:
  3717. try:
  3718. location = eval(dia_box.location)
  3719. if not isinstance(location, tuple):
  3720. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3721. return
  3722. if dia_box.reference == 'rel':
  3723. rel_x = self.mouse[0] + location[0]
  3724. rel_y = self.mouse[1] + location[1]
  3725. location = (rel_x, rel_y)
  3726. self.defaults['global_jump_ref'] = dia_box.reference
  3727. except Exception:
  3728. return
  3729. else:
  3730. return
  3731. else:
  3732. location = custom_location
  3733. self.jump_signal.emit(location)
  3734. if fit_center:
  3735. self.plotcanvas.fit_center(loc=location)
  3736. cursor = QtGui.QCursor()
  3737. if self.is_legacy is False:
  3738. # I don't know where those differences come from but they are constant for the current
  3739. # execution of the application and they are multiples of a value around 0.0263mm.
  3740. # In a random way sometimes they are more sometimes they are less
  3741. # if units == 'MM':
  3742. # cal_factor = 0.0263
  3743. # else:
  3744. # cal_factor = 0.0263 / 25.4
  3745. cal_location = (location[0], location[1])
  3746. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3747. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3748. j_pos = (
  3749. int(canvas_origin.x() + round(jump_loc[0])),
  3750. int(canvas_origin.y() + round(jump_loc[1]))
  3751. )
  3752. cursor.setPos(j_pos[0], j_pos[1])
  3753. else:
  3754. # find the canvas origin which is in the top left corner
  3755. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3756. # determine the coordinates for the lowest left point of the canvas
  3757. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3758. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3759. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3760. # canvas) and the point (width, height) is in the top-right location
  3761. loc = self.plotcanvas.axes.transData.transform_point(location)
  3762. j_pos = (
  3763. int(x0 + loc[0]),
  3764. int(y0 - loc[1])
  3765. )
  3766. cursor.setPos(j_pos[0], j_pos[1])
  3767. self.plotcanvas.mouse = [location[0], location[1]]
  3768. if self.defaults["global_cursor_color_enabled"] is True:
  3769. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3770. else:
  3771. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3772. if self.grid_status():
  3773. # Update cursor
  3774. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3775. symbol='++', edge_color=self.cursor_color_3D,
  3776. edge_width=self.defaults["global_cursor_width"],
  3777. size=self.defaults["global_cursor_size"])
  3778. # Set the relative position label
  3779. dx = location[0] - float(self.rel_point1[0])
  3780. dy = location[1] - float(self.rel_point1[1])
  3781. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3782. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3783. # # Set the position label
  3784. #
  3785. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3786. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3787. units = self.defaults["units"].lower()
  3788. self.plotcanvas.text_hud.text = \
  3789. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3790. dx, units, dy, units, location[0], units, location[1], units)
  3791. self.inform.emit('[success] %s' % _("Done."))
  3792. return location
  3793. def on_locate(self, obj, fit_center=True):
  3794. """
  3795. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3796. :param obj: The object on which to locate certain points
  3797. :param fit_center: If to fit view. Boolean.
  3798. :return: A point location. (x, y) tuple.
  3799. """
  3800. self.defaults.report_usage("on_locate()")
  3801. if obj is None:
  3802. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3803. return 'fail'
  3804. class DialogBoxChoice(QtWidgets.QDialog):
  3805. def __init__(self, title=None, icon=None, choice='bl'):
  3806. """
  3807. :param title: string with the window title
  3808. """
  3809. super(DialogBoxChoice, self).__init__()
  3810. self.ok = False
  3811. self.setWindowIcon(icon)
  3812. self.setWindowTitle(str(title))
  3813. self.form = QtWidgets.QFormLayout(self)
  3814. self.ref_radio = RadioSet([
  3815. {"label": _("Bottom-Left"), "value": "bl"},
  3816. {"label": _("Top-Left"), "value": "tl"},
  3817. {"label": _("Bottom-Right"), "value": "br"},
  3818. {"label": _("Top-Right"), "value": "tr"},
  3819. {"label": _("Center"), "value": "c"}
  3820. ], orientation='vertical', stretch=False)
  3821. self.ref_radio.set_value(choice)
  3822. self.form.addRow(self.ref_radio)
  3823. self.button_box = QtWidgets.QDialogButtonBox(
  3824. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3825. Qt.Horizontal, parent=self)
  3826. self.form.addRow(self.button_box)
  3827. self.button_box.accepted.connect(self.accept)
  3828. self.button_box.rejected.connect(self.reject)
  3829. if self.exec_() == QtWidgets.QDialog.Accepted:
  3830. self.ok = True
  3831. self.location_point = self.ref_radio.get_value()
  3832. else:
  3833. self.ok = False
  3834. self.location_point = None
  3835. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3836. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3837. choice=self.defaults['global_locate_pt'])
  3838. if dia_box.ok is True:
  3839. try:
  3840. location_point = dia_box.location_point
  3841. self.defaults['global_locate_pt'] = dia_box.location_point
  3842. except Exception:
  3843. return
  3844. else:
  3845. return
  3846. loc_b = obj.bounds()
  3847. if location_point == 'bl':
  3848. location = (loc_b[0], loc_b[1])
  3849. elif location_point == 'tl':
  3850. location = (loc_b[0], loc_b[3])
  3851. elif location_point == 'br':
  3852. location = (loc_b[2], loc_b[1])
  3853. elif location_point == 'tr':
  3854. location = (loc_b[2], loc_b[3])
  3855. else:
  3856. # center
  3857. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3858. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3859. location = (cx, cy)
  3860. self.locate_signal.emit(location, location_point)
  3861. if fit_center:
  3862. self.plotcanvas.fit_center(loc=location)
  3863. cursor = QtGui.QCursor()
  3864. if self.is_legacy is False:
  3865. # I don't know where those differences come from but they are constant for the current
  3866. # execution of the application and they are multiples of a value around 0.0263mm.
  3867. # In a random way sometimes they are more sometimes they are less
  3868. # if units == 'MM':
  3869. # cal_factor = 0.0263
  3870. # else:
  3871. # cal_factor = 0.0263 / 25.4
  3872. cal_location = (location[0], location[1])
  3873. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3874. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3875. j_pos = (
  3876. int(canvas_origin.x() + round(jump_loc[0])),
  3877. int(canvas_origin.y() + round(jump_loc[1]))
  3878. )
  3879. cursor.setPos(j_pos[0], j_pos[1])
  3880. else:
  3881. # find the canvas origin which is in the top left corner
  3882. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3883. # determine the coordinates for the lowest left point of the canvas
  3884. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3885. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3886. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3887. # canvas) and the point (width, height) is in the top-right location
  3888. loc = self.plotcanvas.axes.transData.transform_point(location)
  3889. j_pos = (
  3890. int(x0 + loc[0]),
  3891. int(y0 - loc[1])
  3892. )
  3893. cursor.setPos(j_pos[0], j_pos[1])
  3894. self.plotcanvas.mouse = [location[0], location[1]]
  3895. if self.defaults["global_cursor_color_enabled"] is True:
  3896. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3897. else:
  3898. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3899. if self.grid_status():
  3900. # Update cursor
  3901. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3902. symbol='++', edge_color=self.cursor_color_3D,
  3903. edge_width=self.defaults["global_cursor_width"],
  3904. size=self.defaults["global_cursor_size"])
  3905. # Set the relative position label
  3906. self.dx = location[0] - float(self.rel_point1[0])
  3907. self.dy = location[1] - float(self.rel_point1[1])
  3908. # Set the position label
  3909. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3910. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3911. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3912. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3913. units = self.defaults["units"].lower()
  3914. self.plotcanvas.text_hud.text = \
  3915. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3916. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3917. self.inform.emit('[success] %s' % _("Done."))
  3918. return location
  3919. def on_copy_command(self):
  3920. """
  3921. Will copy a selection of objects, creating new objects.
  3922. :return:
  3923. """
  3924. self.defaults.report_usage("on_copy_command()")
  3925. def initialize(obj_init, app):
  3926. """
  3927. :param obj_init: the new object
  3928. :type obj_init: class
  3929. :param app: An instance of the App class
  3930. :type app: App
  3931. :return: None
  3932. :rtype:
  3933. """
  3934. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3935. try:
  3936. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3937. except AttributeError:
  3938. pass
  3939. try:
  3940. obj_init.apertures = deepcopy(obj.apertures)
  3941. except AttributeError:
  3942. pass
  3943. try:
  3944. if obj.tools:
  3945. obj_init.tools = deepcopy(obj.tools)
  3946. except Exception as err:
  3947. log.debug("App.on_copy_command() --> %s" % str(err))
  3948. try:
  3949. obj_init.source_file = deepcopy(obj.source_file)
  3950. except (AttributeError, TypeError):
  3951. pass
  3952. def initialize_excellon(obj_init, app):
  3953. obj_init.source_file = deepcopy(obj.source_file)
  3954. obj_init.tools = deepcopy(obj.tools)
  3955. # drills are offset, so they need to be deep copied
  3956. obj_init.drills = deepcopy(obj.drills)
  3957. # slots are offset, so they need to be deep copied
  3958. obj_init.slots = deepcopy(obj.slots)
  3959. obj_init.create_geometry()
  3960. def initialize_script(obj_init, app_obj):
  3961. obj_init.source_file = deepcopy(obj.source_file)
  3962. def initialize_document(obj_init, app_obj):
  3963. obj_init.source_file = deepcopy(obj.source_file)
  3964. for obj in self.collection.get_selected():
  3965. obj_name = obj.options["name"]
  3966. try:
  3967. if isinstance(obj, ExcellonObject):
  3968. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3969. elif isinstance(obj, GerberObject):
  3970. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  3971. elif isinstance(obj, GeometryObject):
  3972. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  3973. elif isinstance(obj, ScriptObject):
  3974. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  3975. elif isinstance(obj, DocumentObject):
  3976. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  3977. except Exception as e:
  3978. return "Operation failed: %s" % str(e)
  3979. def on_copy_object2(self, custom_name):
  3980. def initialize_geometry(obj_init, app):
  3981. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3982. try:
  3983. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3984. except AttributeError:
  3985. pass
  3986. try:
  3987. obj_init.apertures = deepcopy(obj.apertures)
  3988. except AttributeError:
  3989. pass
  3990. try:
  3991. if obj.tools:
  3992. obj_init.tools = deepcopy(obj.tools)
  3993. except Exception as ee:
  3994. log.debug("on_copy_object2() --> %s" % str(ee))
  3995. def initialize_gerber(obj_init, app):
  3996. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3997. obj_init.apertures = deepcopy(obj.apertures)
  3998. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3999. def initialize_excellon(obj_init, app):
  4000. obj_init.tools = deepcopy(obj.tools)
  4001. # drills are offset, so they need to be deep copied
  4002. obj_init.drills = deepcopy(obj.drills)
  4003. # slots are offset, so they need to be deep copied
  4004. obj_init.slots = deepcopy(obj.slots)
  4005. obj_init.create_geometry()
  4006. for obj in self.collection.get_selected():
  4007. obj_name = obj.options["name"]
  4008. try:
  4009. if isinstance(obj, ExcellonObject):
  4010. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4011. elif isinstance(obj, GerberObject):
  4012. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4013. elif isinstance(obj, GeometryObject):
  4014. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4015. except Exception as er:
  4016. return "Operation failed: %s" % str(er)
  4017. def on_rename_object(self, text):
  4018. """
  4019. Will rename an object.
  4020. :param text: New name for the object.
  4021. :return:
  4022. """
  4023. self.defaults.report_usage("on_rename_object()")
  4024. named_obj = self.collection.get_active()
  4025. for obj in named_obj:
  4026. if obj is list:
  4027. self.on_rename_object(text)
  4028. else:
  4029. try:
  4030. obj.options['name'] = text
  4031. except Exception as e:
  4032. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4033. def convert_any2geo(self):
  4034. """
  4035. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4036. :return:
  4037. """
  4038. self.defaults.report_usage("convert_any2geo()")
  4039. def initialize(obj_init, app):
  4040. obj_init.solid_geometry = obj.solid_geometry
  4041. try:
  4042. obj_init.follow_geometry = obj.follow_geometry
  4043. except AttributeError:
  4044. pass
  4045. try:
  4046. obj_init.apertures = obj.apertures
  4047. except AttributeError:
  4048. pass
  4049. try:
  4050. if obj.tools:
  4051. obj_init.tools = obj.tools
  4052. except AttributeError:
  4053. pass
  4054. def initialize_excellon(obj_init, app):
  4055. # objs = self.collection.get_selected()
  4056. # GeometryObject.merge(objs, obj)
  4057. solid_geo = []
  4058. for tool in obj.tools:
  4059. for geo in obj.tools[tool]['solid_geometry']:
  4060. solid_geo.append(geo)
  4061. obj_init.solid_geometry = deepcopy(solid_geo)
  4062. if not self.collection.get_selected():
  4063. log.warning("App.convert_any2geo --> No object selected")
  4064. self.inform.emit('[WARNING_NOTCL] %s' %
  4065. _("No object is selected. Select an object and try again."))
  4066. return
  4067. for obj in self.collection.get_selected():
  4068. obj_name = obj.options["name"]
  4069. try:
  4070. if isinstance(obj, ExcellonObject):
  4071. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4072. else:
  4073. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4074. except Exception as e:
  4075. return "Operation failed: %s" % str(e)
  4076. def convert_any2gerber(self):
  4077. """
  4078. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4079. :return:
  4080. """
  4081. self.defaults.report_usage("convert_any2gerber()")
  4082. def initialize_geometry(obj_init, app):
  4083. apertures = {}
  4084. apid = 0
  4085. apertures[str(apid)] = {}
  4086. apertures[str(apid)]['geometry'] = []
  4087. for obj_orig in obj.solid_geometry:
  4088. new_elem = {}
  4089. new_elem['solid'] = obj_orig
  4090. try:
  4091. new_elem['follow'] = obj_orig.exterior
  4092. except AttributeError:
  4093. pass
  4094. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4095. apertures[str(apid)]['size'] = 0.0
  4096. apertures[str(apid)]['type'] = 'C'
  4097. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4098. obj_init.apertures = deepcopy(apertures)
  4099. def initialize_excellon(obj_init, app):
  4100. apertures = {}
  4101. apid = 10
  4102. for tool in obj.tools:
  4103. apertures[str(apid)] = {}
  4104. apertures[str(apid)]['geometry'] = []
  4105. for geo in obj.tools[tool]['solid_geometry']:
  4106. new_el = {}
  4107. new_el['solid'] = geo
  4108. new_el['follow'] = geo.exterior
  4109. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4110. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4111. apertures[str(apid)]['type'] = 'C'
  4112. apid += 1
  4113. # create solid_geometry
  4114. solid_geometry = []
  4115. for apid in apertures:
  4116. for geo_el in apertures[apid]['geometry']:
  4117. solid_geometry.append(geo_el['solid'])
  4118. solid_geometry = MultiPolygon(solid_geometry)
  4119. solid_geometry = solid_geometry.buffer(0.0000001)
  4120. obj_init.solid_geometry = deepcopy(solid_geometry)
  4121. obj_init.apertures = deepcopy(apertures)
  4122. # clear the working objects (perhaps not necessary due of Python GC)
  4123. apertures.clear()
  4124. if not self.collection.get_selected():
  4125. log.warning("App.convert_any2gerber --> No object selected")
  4126. self.inform.emit('[WARNING_NOTCL] %s' %
  4127. _("No object is selected. Select an object and try again."))
  4128. return
  4129. for obj in self.collection.get_selected():
  4130. obj_name = obj.options["name"]
  4131. try:
  4132. if isinstance(obj, ExcellonObject):
  4133. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4134. elif isinstance(obj, GeometryObject):
  4135. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4136. else:
  4137. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4138. except Exception as e:
  4139. return "Operation failed: %s" % str(e)
  4140. def abort_all_tasks(self):
  4141. """
  4142. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4143. on the first possible occasion.
  4144. :return:
  4145. """
  4146. if self.abort_flag is False:
  4147. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4148. self.abort_flag = True
  4149. self.cleanup.emit()
  4150. def app_is_idle(self):
  4151. if self.abort_flag:
  4152. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4153. self.abort_flag = False
  4154. def on_selectall(self):
  4155. """
  4156. Will draw a selection box shape around the selected objects.
  4157. :return:
  4158. """
  4159. self.defaults.report_usage("on_selectall()")
  4160. # delete the possible selection box around a possible selected object
  4161. self.delete_selection_shape()
  4162. for name in self.collection.get_names():
  4163. self.collection.set_active(name)
  4164. curr_sel_obj = self.collection.get_by_name(name)
  4165. # create the selection box around the selected object
  4166. if self.defaults['global_selection_shape'] is True:
  4167. self.draw_selection_shape(curr_sel_obj)
  4168. def on_preferences(self):
  4169. """
  4170. Adds the Preferences in a Tab in Plot Area
  4171. :return:
  4172. """
  4173. # add the tab if it was closed
  4174. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4175. # delete the absolute and relative position and messages in the infobar
  4176. self.ui.position_label.setText("")
  4177. # self.ui.rel_position_label.setText("")
  4178. # Switch plot_area to preferences page
  4179. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4180. # self.ui.show()
  4181. # detect changes in the preferences
  4182. for idx in range(self.ui.pref_tab_area.count()):
  4183. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4184. try:
  4185. try:
  4186. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4187. except (TypeError, AttributeError):
  4188. pass
  4189. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4190. except AttributeError:
  4191. pass
  4192. try:
  4193. try:
  4194. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4195. except (TypeError, AttributeError):
  4196. pass
  4197. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4198. except AttributeError:
  4199. pass
  4200. try:
  4201. try:
  4202. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4203. except (TypeError, AttributeError):
  4204. pass
  4205. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4206. except AttributeError:
  4207. pass
  4208. try:
  4209. try:
  4210. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4211. except (TypeError, AttributeError):
  4212. pass
  4213. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4214. except AttributeError:
  4215. pass
  4216. try:
  4217. try:
  4218. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4219. except (TypeError, AttributeError):
  4220. pass
  4221. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4222. except AttributeError:
  4223. pass
  4224. def on_tools_database(self, source='app'):
  4225. """
  4226. Adds the Tools Database in a Tab in Plot Area.
  4227. :return:
  4228. """
  4229. for idx in range(self.ui.plot_tab_area.count()):
  4230. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4231. # there can be only one instance of Tools Database at one time
  4232. return
  4233. if source == 'app':
  4234. self.tools_db_tab = ToolsDB2(
  4235. app=self,
  4236. parent=self.ui,
  4237. callback_on_edited=self.on_tools_db_edited,
  4238. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4239. )
  4240. elif source == 'ncc':
  4241. self.tools_db_tab = ToolsDB2(
  4242. app=self,
  4243. parent=self.ui,
  4244. callback_on_edited=self.on_tools_db_edited,
  4245. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4246. )
  4247. elif source == 'paint':
  4248. self.tools_db_tab = ToolsDB2(
  4249. app=self,
  4250. parent=self.ui,
  4251. callback_on_edited=self.on_tools_db_edited,
  4252. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4253. )
  4254. elif source == 'iso':
  4255. self.tools_db_tab = ToolsDB2(
  4256. app=self,
  4257. parent=self.ui,
  4258. callback_on_edited=self.on_tools_db_edited,
  4259. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4260. )
  4261. # add the tab if it was closed
  4262. try:
  4263. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4264. self.tools_db_tab.setObjectName("database_tab")
  4265. except Exception as e:
  4266. log.debug("App.on_tools_database() --> %s" % str(e))
  4267. return
  4268. # delete the absolute and relative position and messages in the infobar
  4269. self.ui.position_label.setText("")
  4270. # self.ui.rel_position_label.setText("")
  4271. # Switch plot_area to preferences page
  4272. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4273. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4274. self.tools_db_tab.ui_connect()
  4275. def on_tools_db_edited(self):
  4276. """
  4277. Executed whenever a tool is edited in Tools Database.
  4278. Will color the text of the Tools Database tab to Red color.
  4279. :return:
  4280. """
  4281. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4282. for idx in range(self.ui.plot_tab_area.count()):
  4283. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4284. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4285. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4286. self.tools_db_changed_flag = True
  4287. def on_geometry_tool_add_from_db_executed(self, tool):
  4288. """
  4289. Here add the tool from DB in the selected geometry object.
  4290. :return:
  4291. """
  4292. tool_from_db = deepcopy(tool)
  4293. obj = self.collection.get_active()
  4294. if obj.kind == 'geometry':
  4295. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4296. # close the tab and delete it
  4297. for idx in range(self.ui.plot_tab_area.count()):
  4298. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4299. wdg = self.ui.plot_tab_area.widget(idx)
  4300. wdg.deleteLater()
  4301. self.ui.plot_tab_area.removeTab(idx)
  4302. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4303. elif obj.kind == 'gerber':
  4304. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4305. # close the tab and delete it
  4306. for idx in range(self.ui.plot_tab_area.count()):
  4307. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4308. wdg = self.ui.plot_tab_area.widget(idx)
  4309. wdg.deleteLater()
  4310. self.ui.plot_tab_area.removeTab(idx)
  4311. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4312. else:
  4313. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4314. def on_plot_area_tab_closed(self, tab_obj_name):
  4315. """
  4316. Executed whenever a QTab is closed in the Plot Area.
  4317. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4318. :return:
  4319. """
  4320. if tab_obj_name == "preferences_tab":
  4321. self.preferencesUiManager.on_close_preferences_tab()
  4322. elif tab_obj_name == "database_tab":
  4323. # disconnect the signals from the table widget in tab
  4324. self.tools_db_tab.ui_disconnect()
  4325. if self.tools_db_changed_flag is True:
  4326. msgbox = QtWidgets.QMessageBox()
  4327. msgbox.setText(_("One or more Tools are edited.\n"
  4328. "Do you want to update the Tools Database?"))
  4329. msgbox.setWindowTitle(_("Save Tools Database"))
  4330. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4331. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4332. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4333. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4334. msgbox.setDefaultButton(bt_yes)
  4335. msgbox.exec_()
  4336. response = msgbox.clickedButton()
  4337. if response == bt_yes:
  4338. self.tools_db_tab.on_save_tools_db()
  4339. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4340. else:
  4341. self.tools_db_changed_flag = False
  4342. self.inform.emit('')
  4343. return
  4344. self.tools_db_tab.deleteLater()
  4345. elif tab_obj_name == "text_editor_tab":
  4346. self.toggle_codeeditor = False
  4347. elif tab_obj_name == "bookmarks_tab":
  4348. self.book_dialog_tab.rebuild_actions()
  4349. self.book_dialog_tab.deleteLater()
  4350. else:
  4351. return
  4352. # def on_plotarea_tab_closed(self, tab_idx):
  4353. # """
  4354. #
  4355. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4356. # :return:
  4357. # """
  4358. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4359. #
  4360. # if widget is not None:
  4361. # widget.deleteLater()
  4362. # self.ui.plot_tab_area.removeTab(tab_idx)
  4363. def on_flipy(self):
  4364. """
  4365. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4366. :return:
  4367. """
  4368. self.defaults.report_usage("on_flipy()")
  4369. obj_list = self.collection.get_selected()
  4370. xminlist = []
  4371. yminlist = []
  4372. xmaxlist = []
  4373. ymaxlist = []
  4374. if not obj_list:
  4375. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4376. else:
  4377. try:
  4378. # first get a bounding box to fit all
  4379. for obj in obj_list:
  4380. xmin, ymin, xmax, ymax = obj.bounds()
  4381. xminlist.append(xmin)
  4382. yminlist.append(ymin)
  4383. xmaxlist.append(xmax)
  4384. ymaxlist.append(ymax)
  4385. # get the minimum x,y and maximum x,y for all objects selected
  4386. xminimal = min(xminlist)
  4387. yminimal = min(yminlist)
  4388. xmaximal = max(xmaxlist)
  4389. ymaximal = max(ymaxlist)
  4390. px = 0.5 * (xminimal + xmaximal)
  4391. py = 0.5 * (yminimal + ymaximal)
  4392. # execute mirroring
  4393. for obj in obj_list:
  4394. obj.mirror('X', [px, py])
  4395. obj.plot()
  4396. self.app_obj.object_changed.emit(obj)
  4397. self.inform.emit('[success] %s' %
  4398. _("Flip on Y axis done."))
  4399. except Exception as e:
  4400. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4401. return
  4402. def on_flipx(self):
  4403. """
  4404. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4405. :return:
  4406. """
  4407. self.defaults.report_usage("on_flipx()")
  4408. obj_list = self.collection.get_selected()
  4409. xminlist = []
  4410. yminlist = []
  4411. xmaxlist = []
  4412. ymaxlist = []
  4413. if not obj_list:
  4414. self.inform.emit('[WARNING_NOTCL] %s' %
  4415. _("No object selected to Flip on X axis."))
  4416. else:
  4417. try:
  4418. # first get a bounding box to fit all
  4419. for obj in obj_list:
  4420. xmin, ymin, xmax, ymax = obj.bounds()
  4421. xminlist.append(xmin)
  4422. yminlist.append(ymin)
  4423. xmaxlist.append(xmax)
  4424. ymaxlist.append(ymax)
  4425. # get the minimum x,y and maximum x,y for all objects selected
  4426. xminimal = min(xminlist)
  4427. yminimal = min(yminlist)
  4428. xmaximal = max(xmaxlist)
  4429. ymaximal = max(ymaxlist)
  4430. px = 0.5 * (xminimal + xmaximal)
  4431. py = 0.5 * (yminimal + ymaximal)
  4432. # execute mirroring
  4433. for obj in obj_list:
  4434. obj.mirror('Y', [px, py])
  4435. obj.plot()
  4436. self.app_obj.object_changed.emit(obj)
  4437. self.inform.emit('[success] %s' %
  4438. _("Flip on X axis done."))
  4439. except Exception as e:
  4440. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4441. return
  4442. def on_rotate(self, silent=False, preset=None):
  4443. """
  4444. Executed when Options -> Rotate Selection menu entry is clicked.
  4445. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4446. :param preset: A value to be used as predefined angle for rotation.
  4447. :return:
  4448. """
  4449. self.defaults.report_usage("on_rotate()")
  4450. obj_list = self.collection.get_selected()
  4451. xminlist = []
  4452. yminlist = []
  4453. xmaxlist = []
  4454. ymaxlist = []
  4455. if not obj_list:
  4456. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4457. else:
  4458. if silent is False:
  4459. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4460. min=-360, max=360, decimals=4,
  4461. init_val=float(self.defaults['tools_transform_rotate']))
  4462. num, ok = rotatebox.get_value()
  4463. else:
  4464. num = preset
  4465. ok = True
  4466. if ok:
  4467. try:
  4468. # first get a bounding box to fit all
  4469. for obj in obj_list:
  4470. xmin, ymin, xmax, ymax = obj.bounds()
  4471. xminlist.append(xmin)
  4472. yminlist.append(ymin)
  4473. xmaxlist.append(xmax)
  4474. ymaxlist.append(ymax)
  4475. # get the minimum x,y and maximum x,y for all objects selected
  4476. xminimal = min(xminlist)
  4477. yminimal = min(yminlist)
  4478. xmaximal = max(xmaxlist)
  4479. ymaximal = max(ymaxlist)
  4480. px = 0.5 * (xminimal + xmaximal)
  4481. py = 0.5 * (yminimal + ymaximal)
  4482. for sel_obj in obj_list:
  4483. sel_obj.rotate(-float(num), point=(px, py))
  4484. sel_obj.plot()
  4485. self.app_obj.object_changed.emit(sel_obj)
  4486. self.inform.emit('[success] %s' % _("Rotation done."))
  4487. except Exception as e:
  4488. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4489. return
  4490. def on_skewx(self):
  4491. """
  4492. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4493. :return:
  4494. """
  4495. self.defaults.report_usage("on_skewx()")
  4496. obj_list = self.collection.get_selected()
  4497. xminlist = []
  4498. yminlist = []
  4499. if not obj_list:
  4500. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4501. else:
  4502. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4503. min=-360, max=360, decimals=4,
  4504. init_val=float(self.defaults['tools_transform_skew_x']))
  4505. num, ok = skewxbox.get_value()
  4506. if ok:
  4507. # first get a bounding box to fit all
  4508. for obj in obj_list:
  4509. xmin, ymin, xmax, ymax = obj.bounds()
  4510. xminlist.append(xmin)
  4511. yminlist.append(ymin)
  4512. # get the minimum x,y and maximum x,y for all objects selected
  4513. xminimal = min(xminlist)
  4514. yminimal = min(yminlist)
  4515. for obj in obj_list:
  4516. obj.skew(num, 0, point=(xminimal, yminimal))
  4517. obj.plot()
  4518. self.app_obj.object_changed.emit(obj)
  4519. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4520. def on_skewy(self):
  4521. """
  4522. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4523. :return:
  4524. """
  4525. self.defaults.report_usage("on_skewy()")
  4526. obj_list = self.collection.get_selected()
  4527. xminlist = []
  4528. yminlist = []
  4529. if not obj_list:
  4530. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4531. else:
  4532. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4533. min=-360, max=360, decimals=4,
  4534. init_val=float(self.defaults['tools_transform_skew_y']))
  4535. num, ok = skewybox.get_value()
  4536. if ok:
  4537. # first get a bounding box to fit all
  4538. for obj in obj_list:
  4539. xmin, ymin, xmax, ymax = obj.bounds()
  4540. xminlist.append(xmin)
  4541. yminlist.append(ymin)
  4542. # get the minimum x,y and maximum x,y for all objects selected
  4543. xminimal = min(xminlist)
  4544. yminimal = min(yminlist)
  4545. for obj in obj_list:
  4546. obj.skew(0, num, point=(xminimal, yminimal))
  4547. obj.plot()
  4548. self.app_obj.object_changed.emit(obj)
  4549. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4550. def on_plots_updated(self):
  4551. """
  4552. Callback used to report when the plots have changed.
  4553. Adjust axes and zooms to fit.
  4554. :return: None
  4555. """
  4556. if self.is_legacy is False:
  4557. self.plotcanvas.update()
  4558. else:
  4559. self.plotcanvas.auto_adjust_axes()
  4560. self.on_zoom_fit()
  4561. self.collection.update_view()
  4562. # self.inform.emit(_("Plots updated ..."))
  4563. def on_toolbar_replot(self):
  4564. """
  4565. Callback for toolbar button. Re-plots all objects.
  4566. :return: None
  4567. """
  4568. self.log.debug("on_toolbar_replot()")
  4569. try:
  4570. self.collection.get_active().read_form()
  4571. except AttributeError:
  4572. self.log.debug("on_toolbar_replot(): AttributeError")
  4573. pass
  4574. self.plot_all()
  4575. def grid_status(self):
  4576. return True if self.ui.grid_snap_btn.isChecked() else False
  4577. def populate_cmenu_grids(self):
  4578. units = self.defaults['units'].lower()
  4579. # for act in self.ui.cmenu_gridmenu.actions():
  4580. # act.triggered.disconnect()
  4581. self.ui.cmenu_gridmenu.clear()
  4582. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4583. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4584. _("Grid On/Off"))
  4585. grid_toggle.setCheckable(True)
  4586. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4587. self.ui.cmenu_gridmenu.addSeparator()
  4588. for grid in sorted_list:
  4589. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4590. "%s" % str(grid))
  4591. action.triggered.connect(self.set_grid)
  4592. self.ui.cmenu_gridmenu.addSeparator()
  4593. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4594. _("Add"))
  4595. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4596. _("Delete"))
  4597. grid_add.triggered.connect(self.on_grid_add)
  4598. grid_delete.triggered.connect(self.on_grid_delete)
  4599. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4600. def set_grid(self):
  4601. menu_action = self.sender()
  4602. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4603. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4604. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4605. def on_grid_add(self):
  4606. # ## Current application units in lower Case
  4607. units = self.defaults['units'].lower()
  4608. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4609. text=_('Enter a Grid Value:'),
  4610. min=0.0000, max=99.9999, decimals=4)
  4611. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4612. val, ok = grid_add_popup.get_value()
  4613. if ok:
  4614. if float(val) == 0:
  4615. self.inform.emit('[WARNING_NOTCL] %s' %
  4616. _("Please enter a grid value with non-zero value, in Float format."))
  4617. return
  4618. else:
  4619. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4620. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4621. self.inform.emit('[success] %s...' % _("New Grid added"))
  4622. else:
  4623. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4624. else:
  4625. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4626. def on_grid_delete(self):
  4627. # ## Current application units in lower Case
  4628. units = self.defaults['units'].lower()
  4629. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4630. text='Enter a Grid Value:',
  4631. min=0.0000, max=99.9999, decimals=4)
  4632. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4633. val, ok = grid_del_popup.get_value()
  4634. if ok:
  4635. if float(val) == 0:
  4636. self.inform.emit('[WARNING_NOTCL] %s' %
  4637. _("Please enter a grid value with non-zero value, in Float format."))
  4638. return
  4639. else:
  4640. try:
  4641. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4642. except ValueError:
  4643. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4644. return
  4645. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4646. else:
  4647. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4648. def on_shortcut_list(self):
  4649. self.defaults.report_usage("on_shortcut_list()")
  4650. # add the tab if it was closed
  4651. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4652. # delete the absolute and relative position and messages in the infobar
  4653. self.ui.position_label.setText("")
  4654. # self.ui.rel_position_label.setText("")
  4655. # Switch plot_area to preferences page
  4656. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4657. # self.ui.show()
  4658. def on_select_tab(self, name):
  4659. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4660. if self.ui.splitter.sizes()[0] == 0:
  4661. self.ui.splitter.setSizes([1, 1])
  4662. else:
  4663. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4664. self.ui.splitter.setSizes([0, 1])
  4665. if name == 'project':
  4666. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4667. elif name == 'selected':
  4668. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4669. elif name == 'tool':
  4670. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4671. def on_copy_name(self):
  4672. self.defaults.report_usage("on_copy_name()")
  4673. obj = self.collection.get_active()
  4674. try:
  4675. name = obj.options["name"]
  4676. except AttributeError:
  4677. log.debug("on_copy_name() --> No object selected to copy it's name")
  4678. self.inform.emit('[WARNING_NOTCL]%s' %
  4679. _(" No object selected to copy it's name"))
  4680. return
  4681. self.clipboard.setText(name)
  4682. self.inform.emit(_("Name copied on clipboard ..."))
  4683. def on_mouse_click_over_plot(self, event):
  4684. """
  4685. Default actions are:
  4686. :param event: Contains information about the event, like which button
  4687. was clicked, the pixel coordinates and the axes coordinates.
  4688. :return: None
  4689. """
  4690. self.pos = []
  4691. if self.is_legacy is False:
  4692. event_pos = event.pos
  4693. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4694. # # Set the mouse button for panning
  4695. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4696. else:
  4697. event_pos = (event.xdata, event.ydata)
  4698. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4699. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4700. # So it can receive key presses
  4701. self.plotcanvas.native.setFocus()
  4702. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4703. if self.grid_status():
  4704. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4705. else:
  4706. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4707. try:
  4708. if event.button == 1:
  4709. # Reset here the relative coordinates so there is a new reference on the click position
  4710. if self.rel_point1 is None:
  4711. self.rel_point1 = self.pos
  4712. else:
  4713. self.rel_point2 = copy(self.rel_point1)
  4714. self.rel_point1 = self.pos
  4715. self.on_mouse_move_over_plot(event, origin_click=True)
  4716. except Exception as e:
  4717. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4718. def on_mouse_double_click_over_plot(self, event):
  4719. if event.button == 1:
  4720. self.doubleclick = True
  4721. def on_mouse_move_over_plot(self, event, origin_click=None):
  4722. """
  4723. Callback for the mouse motion event over the plot.
  4724. :param event: Contains information about the event.
  4725. :param origin_click
  4726. :return: None
  4727. """
  4728. if self.is_legacy is False:
  4729. event_pos = event.pos
  4730. if self.defaults["global_pan_button"] == '2':
  4731. pan_button = 2
  4732. else:
  4733. pan_button = 3
  4734. self.event_is_dragging = event.is_dragging
  4735. else:
  4736. event_pos = (event.xdata, event.ydata)
  4737. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4738. if self.defaults["global_pan_button"] == '2':
  4739. pan_button = 3
  4740. else:
  4741. pan_button = 2
  4742. self.event_is_dragging = self.plotcanvas.is_dragging
  4743. # So it can receive key presses but not when the Tcl Shell is active
  4744. if not self.ui.shell_dock.isVisible():
  4745. if not self.plotcanvas.native.hasFocus():
  4746. self.plotcanvas.native.setFocus()
  4747. self.pos_jump = event_pos
  4748. self.ui.popMenu.mouse_is_panning = False
  4749. if origin_click is None:
  4750. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4751. if event.button == pan_button and self.event_is_dragging == 1:
  4752. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4753. if self.ui.popMenu.popup_active:
  4754. self.ui.popMenu.popup_active = False
  4755. return
  4756. self.ui.popMenu.mouse_is_panning = True
  4757. return
  4758. if self.rel_point1 is not None:
  4759. try: # May fail in case mouse not within axes
  4760. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4761. if pos_canvas[0] is None or pos_canvas[1] is None:
  4762. return
  4763. if self.grid_status():
  4764. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4765. # Update cursor
  4766. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4767. symbol='++', edge_color=self.cursor_color_3D,
  4768. edge_width=self.defaults["global_cursor_width"],
  4769. size=self.defaults["global_cursor_size"])
  4770. else:
  4771. pos = (pos_canvas[0], pos_canvas[1])
  4772. self.dx = pos[0] - float(self.rel_point1[0])
  4773. self.dy = pos[1] - float(self.rel_point1[1])
  4774. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4775. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4776. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4777. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4778. units = self.defaults["units"].lower()
  4779. self.plotcanvas.text_hud.text = \
  4780. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4781. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4782. self.mouse = [pos[0], pos[1]]
  4783. # if the mouse is moved and the LMB is clicked then the action is a selection
  4784. if self.event_is_dragging == 1 and event.button == 1:
  4785. self.delete_selection_shape()
  4786. if self.dx < 0:
  4787. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4788. face_color=self.defaults['global_alt_sel_fill'])
  4789. self.selection_type = False
  4790. elif self.dx >= 0:
  4791. self.draw_moving_selection_shape(self.pos, pos)
  4792. self.selection_type = True
  4793. else:
  4794. self.selection_type = None
  4795. else:
  4796. self.selection_type = None
  4797. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4798. if self.defaults['global_hover']:
  4799. for obj in self.collection.get_list():
  4800. try:
  4801. # select the object(s) only if it is enabled (plotted)
  4802. if obj.options['plot']:
  4803. if obj not in self.collection.get_selected():
  4804. poly_obj = Polygon(
  4805. [(obj.options['xmin'], obj.options['ymin']),
  4806. (obj.options['xmax'], obj.options['ymin']),
  4807. (obj.options['xmax'], obj.options['ymax']),
  4808. (obj.options['xmin'], obj.options['ymax'])]
  4809. )
  4810. if Point(pos).within(poly_obj):
  4811. if obj.isHovering is False:
  4812. obj.isHovering = True
  4813. obj.notHovering = True
  4814. # create the selection box around the selected object
  4815. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4816. else:
  4817. if obj.notHovering is True:
  4818. obj.notHovering = False
  4819. obj.isHovering = False
  4820. self.delete_hover_shape()
  4821. except Exception:
  4822. # the Exception here will happen if we try to select on screen and we have an
  4823. # newly (and empty) just created Geometry or Excellon object that do not have the
  4824. # xmin, xmax, ymin, ymax options.
  4825. # In this case poly_obj creation (see above) will fail
  4826. pass
  4827. except Exception as e:
  4828. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4829. self.ui.position_label.setText("")
  4830. # self.ui.rel_position_label.setText("")
  4831. self.mouse = None
  4832. def on_mouse_click_release_over_plot(self, event):
  4833. """
  4834. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4835. and has been registered in ''self.__init__()''.
  4836. :param event: contains information about the event.
  4837. :return:
  4838. """
  4839. if self.is_legacy is False:
  4840. event_pos = event.pos
  4841. right_button = 2
  4842. else:
  4843. event_pos = (event.xdata, event.ydata)
  4844. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4845. right_button = 3
  4846. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4847. if self.grid_status():
  4848. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4849. else:
  4850. pos = (pos_canvas[0], pos_canvas[1])
  4851. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4852. # canvas menu
  4853. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4854. self.ui.popMenu.mouse_is_panning = False
  4855. self.cursor = QtGui.QCursor()
  4856. self.populate_cmenu_grids()
  4857. self.ui.popMenu.popup(self.cursor.pos())
  4858. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4859. # selection and then select a type of selection ("enclosing" or "touching")
  4860. if event.button == 1: # left click
  4861. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4862. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4863. if modifiers == QtCore.Qt.ShiftModifier:
  4864. # do not auto open the Project Tab
  4865. self.click_noproject = True
  4866. self.clipboard.setText(
  4867. self.defaults["global_point_clipboard_format"] %
  4868. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4869. )
  4870. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4871. return
  4872. if self.doubleclick is True:
  4873. self.doubleclick = False
  4874. if self.collection.get_selected():
  4875. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4876. if self.ui.splitter.sizes()[0] == 0:
  4877. self.ui.splitter.setSizes([1, 1])
  4878. try:
  4879. # delete the selection shape(S) as it may be in the way
  4880. self.delete_selection_shape()
  4881. self.delete_hover_shape()
  4882. except Exception as e:
  4883. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4884. return
  4885. else:
  4886. # WORKAROUND for LEGACY MODE
  4887. if self.is_legacy is True:
  4888. # if there is no move on canvas then we have no dragging selection
  4889. if self.dx == 0 or self.dy == 0:
  4890. self.selection_type = None
  4891. if self.selection_type is not None:
  4892. try:
  4893. self.selection_area_handler(self.pos, pos, self.selection_type)
  4894. self.selection_type = None
  4895. except Exception as e:
  4896. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4897. return
  4898. else:
  4899. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4900. if key_modifier == QtCore.Qt.ShiftModifier:
  4901. mod_key = 'Shift'
  4902. elif key_modifier == QtCore.Qt.ControlModifier:
  4903. mod_key = 'Control'
  4904. else:
  4905. mod_key = None
  4906. try:
  4907. if self.command_active is None:
  4908. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4909. # deselect, and if it's not selected then it will be selected
  4910. # If there is no active command (self.command_active is None) then we check if we clicked
  4911. # on a object by checking the bounding limits against mouse click position
  4912. if mod_key == self.defaults["global_mselect_key"]:
  4913. self.select_objects(key='multisel')
  4914. else:
  4915. # If there is no active command (self.command_active is None) then we check if
  4916. # we clicked on a object by checking the bounding limits against mouse click position
  4917. self.select_objects()
  4918. self.delete_hover_shape()
  4919. except Exception as e:
  4920. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4921. return
  4922. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4923. """
  4924. :param start_pos: mouse position when the selection LMB click was done
  4925. :param end_pos: mouse position when the left mouse button is released
  4926. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4927. :return:
  4928. """
  4929. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4930. # delete previous selection shape
  4931. self.delete_selection_shape()
  4932. # make all objects inactive
  4933. self.collection.set_all_inactive()
  4934. for obj in self.collection.get_list():
  4935. try:
  4936. # select the object(s) only if it is enabled (plotted)
  4937. if obj.options['plot']:
  4938. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4939. (obj.options['xmax'], obj.options['ymin']),
  4940. (obj.options['xmax'], obj.options['ymax']),
  4941. (obj.options['xmin'], obj.options['ymax'])])
  4942. if sel_type is True:
  4943. if poly_obj.within(poly_selection):
  4944. # create the selection box around the selected object
  4945. if self.defaults['global_selection_shape'] is True:
  4946. self.draw_selection_shape(obj)
  4947. self.collection.set_active(obj.options['name'])
  4948. else:
  4949. if poly_selection.intersects(poly_obj):
  4950. # create the selection box around the selected object
  4951. if self.defaults['global_selection_shape'] is True:
  4952. self.draw_selection_shape(obj)
  4953. self.collection.set_active(obj.options['name'])
  4954. obj.selection_shape_drawn = True
  4955. except Exception as e:
  4956. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4957. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4958. # In this case poly_obj creation (see above) will fail
  4959. log.debug("App.selection_area_handler() --> %s" % str(e))
  4960. def select_objects(self, key=None):
  4961. """
  4962. Will select objects clicked on canvas
  4963. :param key: for future use in cumulative selection
  4964. :return:
  4965. """
  4966. # list where we store the overlapped objects under our mouse left click position
  4967. if key is None:
  4968. self.objects_under_the_click_list = []
  4969. # Populate the list with the overlapped objects on the click position
  4970. curr_x, curr_y = self.pos
  4971. for obj in self.all_objects_list:
  4972. # ScriptObject and DocumentObject objects can't be selected
  4973. if obj.kind == 'script' or obj.kind == 'document':
  4974. continue
  4975. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  4976. continue
  4977. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4978. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4979. if obj.options['name'] not in self.objects_under_the_click_list:
  4980. if obj.options['plot']:
  4981. # add objects to the objects_under_the_click list only if the object is plotted
  4982. # (active and not disabled)
  4983. self.objects_under_the_click_list.append(obj.options['name'])
  4984. try:
  4985. if self.objects_under_the_click_list:
  4986. curr_sel_obj = self.collection.get_active()
  4987. # case when there is only an object under the click and we toggle it
  4988. if len(self.objects_under_the_click_list) == 1:
  4989. if curr_sel_obj is None:
  4990. self.collection.set_active(self.objects_under_the_click_list[0])
  4991. curr_sel_obj = self.collection.get_active()
  4992. # create the selection box around the selected object
  4993. if self.defaults['global_selection_shape'] is True:
  4994. self.draw_selection_shape(curr_sel_obj)
  4995. curr_sel_obj.selection_shape_drawn = True
  4996. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  4997. self.collection.on_objects_selection(False)
  4998. self.delete_selection_shape()
  4999. curr_sel_obj.selection_shape_drawn = False
  5000. self.collection.set_active(self.objects_under_the_click_list[0])
  5001. curr_sel_obj = self.collection.get_active()
  5002. # create the selection box around the selected object
  5003. if self.defaults['global_selection_shape'] is True:
  5004. self.draw_selection_shape(curr_sel_obj)
  5005. curr_sel_obj.selection_shape_drawn = True
  5006. self.selected_message(curr_sel_obj=curr_sel_obj)
  5007. elif curr_sel_obj.selection_shape_drawn is False:
  5008. if self.defaults['global_selection_shape'] is True:
  5009. self.draw_selection_shape(curr_sel_obj)
  5010. curr_sel_obj.selection_shape_drawn = True
  5011. else:
  5012. self.collection.on_objects_selection(False)
  5013. self.delete_selection_shape()
  5014. if self.call_source != 'app':
  5015. self.call_source = 'app'
  5016. self.selected_message(curr_sel_obj=curr_sel_obj)
  5017. else:
  5018. # If there is no selected object
  5019. # make active the first element of the overlapped objects list
  5020. if self.collection.get_active() is None:
  5021. self.collection.set_active(self.objects_under_the_click_list[0])
  5022. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5023. name_sel_obj = self.collection.get_active().options['name']
  5024. # In case that there is a selected object but it is not in the overlapped object list
  5025. # make that object inactive and activate the first element in the overlapped object list
  5026. if name_sel_obj not in self.objects_under_the_click_list:
  5027. self.collection.set_inactive(name_sel_obj)
  5028. name_sel_obj = self.objects_under_the_click_list[0]
  5029. self.collection.set_active(name_sel_obj)
  5030. else:
  5031. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5032. self.collection.set_all_inactive()
  5033. self.collection.set_active(
  5034. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5035. curr_sel_obj = self.collection.get_active()
  5036. # delete the possible selection box around a possible selected object
  5037. self.delete_selection_shape()
  5038. curr_sel_obj.selection_shape_drawn = False
  5039. # create the selection box around the selected object
  5040. if self.defaults['global_selection_shape'] is True:
  5041. self.draw_selection_shape(curr_sel_obj)
  5042. curr_sel_obj.selection_shape_drawn = True
  5043. self.selected_message(curr_sel_obj=curr_sel_obj)
  5044. else:
  5045. # deselect everything
  5046. self.collection.on_objects_selection(False)
  5047. # delete the possible selection box around a possible selected object
  5048. self.delete_selection_shape()
  5049. for o in self.collection.get_list():
  5050. o.selection_shape_drawn = False
  5051. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5052. # only when working on App
  5053. if self.call_source == 'app':
  5054. if self.click_noproject is False:
  5055. # if the Tool Tab is in focus don't change focus to Project Tab
  5056. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5057. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5058. else:
  5059. # restore auto open the Project Tab
  5060. self.click_noproject = False
  5061. # delete any text in the status bar, implicitly the last object name that was selected
  5062. # self.inform.emit("")
  5063. else:
  5064. self.call_source = 'app'
  5065. except Exception as e:
  5066. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5067. def selected_message(self, curr_sel_obj):
  5068. if curr_sel_obj:
  5069. if curr_sel_obj.kind == 'gerber':
  5070. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5071. color='green',
  5072. name=str(curr_sel_obj.options['name']),
  5073. tx=_("selected"))
  5074. )
  5075. elif curr_sel_obj.kind == 'excellon':
  5076. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5077. color='brown',
  5078. name=str(curr_sel_obj.options['name']),
  5079. tx=_("selected"))
  5080. )
  5081. elif curr_sel_obj.kind == 'cncjob':
  5082. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5083. color='blue',
  5084. name=str(curr_sel_obj.options['name']),
  5085. tx=_("selected"))
  5086. )
  5087. elif curr_sel_obj.kind == 'geometry':
  5088. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5089. color='red',
  5090. name=str(curr_sel_obj.options['name']),
  5091. tx=_("selected"))
  5092. )
  5093. def delete_hover_shape(self):
  5094. self.hover_shapes.clear()
  5095. self.hover_shapes.redraw()
  5096. def draw_hover_shape(self, sel_obj, color=None):
  5097. """
  5098. :param sel_obj: The object for which the hover shape must be drawn
  5099. :param color: The color of the hover shape
  5100. :return: None
  5101. """
  5102. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5103. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5104. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5105. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5106. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5107. if self.defaults['units'].upper() == 'MM':
  5108. hover_rect = hover_rect.buffer(-0.1)
  5109. hover_rect = hover_rect.buffer(0.2)
  5110. else:
  5111. hover_rect = hover_rect.buffer(-0.00393)
  5112. hover_rect = hover_rect.buffer(0.00787)
  5113. # if color:
  5114. # face = Color(color)
  5115. # face.alpha = 0.2
  5116. # outline = Color(color, alpha=0.8)
  5117. # else:
  5118. # face = Color(self.defaults['global_sel_fill'])
  5119. # face.alpha = 0.2
  5120. # outline = self.defaults['global_sel_line']
  5121. if color:
  5122. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5123. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5124. else:
  5125. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5126. outline = self.defaults['global_sel_line']
  5127. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5128. if self.is_legacy is True:
  5129. self.hover_shapes.redraw()
  5130. def delete_selection_shape(self):
  5131. self.move_tool.sel_shapes.clear()
  5132. self.move_tool.sel_shapes.redraw()
  5133. def draw_selection_shape(self, sel_obj, color=None):
  5134. """
  5135. Will draw a selection shape around the selected object.
  5136. :param sel_obj: The object for which the selection shape must be drawn
  5137. :param color: The color for the selection shape.
  5138. :return: None
  5139. """
  5140. if sel_obj is None:
  5141. return
  5142. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5143. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5144. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5145. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5146. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5147. if self.defaults['units'].upper() == 'MM':
  5148. sel_rect = sel_rect.buffer(-0.1)
  5149. sel_rect = sel_rect.buffer(0.2)
  5150. else:
  5151. sel_rect = sel_rect.buffer(-0.00393)
  5152. sel_rect = sel_rect.buffer(0.00787)
  5153. if color:
  5154. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5155. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5156. else:
  5157. if self.is_legacy is False:
  5158. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5159. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5160. else:
  5161. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5162. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5163. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5164. color=outline,
  5165. face_color=face,
  5166. update=True,
  5167. layer=0,
  5168. tolerance=None))
  5169. if self.is_legacy is True:
  5170. self.move_tool.sel_shapes.redraw()
  5171. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5172. """
  5173. Will draw a selection shape when dragging mouse on canvas.
  5174. :param old_coords: Old coordinates
  5175. :param coords: New coordinates
  5176. :param kwargs: Keyword arguments
  5177. :return:
  5178. """
  5179. if 'color' in kwargs:
  5180. color = kwargs['color']
  5181. else:
  5182. color = self.defaults['global_sel_line']
  5183. if 'face_color' in kwargs:
  5184. face_color = kwargs['face_color']
  5185. else:
  5186. face_color = self.defaults['global_sel_fill']
  5187. if 'face_alpha' in kwargs:
  5188. face_alpha = kwargs['face_alpha']
  5189. else:
  5190. face_alpha = 0.3
  5191. x0, y0 = old_coords
  5192. x1, y1 = coords
  5193. pt1 = (x0, y0)
  5194. pt2 = (x1, y0)
  5195. pt3 = (x1, y1)
  5196. pt4 = (x0, y1)
  5197. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5198. # color_t = Color(face_color)
  5199. # color_t.alpha = face_alpha
  5200. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5201. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5202. layer=0, tolerance=None)
  5203. if self.is_legacy is True:
  5204. self.move_tool.sel_shapes.redraw()
  5205. def on_file_new_click(self):
  5206. """
  5207. Callback for menu item File -> New.
  5208. Executed on clicking the Menu -> File -> New Project
  5209. :return:
  5210. """
  5211. if self.collection.get_list() and self.should_we_save:
  5212. msgbox = QtWidgets.QMessageBox()
  5213. # msgbox.setText("<B>Save changes ...</B>")
  5214. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5215. "Creating a New project will delete them.\n"
  5216. "Do you want to Save the project?"))
  5217. msgbox.setWindowTitle(_("Save changes"))
  5218. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5219. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5220. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5221. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5222. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5223. msgbox.setDefaultButton(bt_yes)
  5224. msgbox.exec_()
  5225. response = msgbox.clickedButton()
  5226. if response == bt_yes:
  5227. self.on_file_saveprojectas()
  5228. elif response == bt_cancel:
  5229. return
  5230. elif response == bt_no:
  5231. self.on_file_new()
  5232. else:
  5233. self.on_file_new()
  5234. self.inform.emit('[success] %s...' % _("New Project created"))
  5235. def on_file_new(self, cli=None):
  5236. """
  5237. Returns the application to its startup state. This method is thread-safe.
  5238. :param cli: Boolean. If True this method was run from command line
  5239. :return: None
  5240. """
  5241. self.defaults.report_usage("on_file_new")
  5242. # Remove everything from memory
  5243. App.log.debug("on_file_new()")
  5244. # close any editor that might be open
  5245. if self.call_source != 'app':
  5246. self.editor2object(cleanup=True)
  5247. # ## EDITOR section
  5248. self.geo_editor = FlatCAMGeoEditor(self)
  5249. self.exc_editor = FlatCAMExcEditor(self)
  5250. self.grb_editor = FlatCAMGrbEditor(self)
  5251. # Clear pool
  5252. self.clear_pool()
  5253. for obj in self.collection.get_list():
  5254. # delete shapes left drawn from mark shape_collections, if any
  5255. if isinstance(obj, GerberObject):
  5256. try:
  5257. for el in obj.mark_shapes:
  5258. obj.mark_shapes[el].clear(update=True)
  5259. obj.mark_shapes[el].enabled = False
  5260. del el
  5261. except AttributeError:
  5262. pass
  5263. # also delete annotation shapes, if any
  5264. elif isinstance(obj, CNCJobObject):
  5265. try:
  5266. obj.text_col.enabled = False
  5267. del obj.text_col
  5268. obj.annotation.clear(update=True)
  5269. del obj.annotation
  5270. except AttributeError:
  5271. pass
  5272. # delete the exclusion areas
  5273. self.exc_areas.clear_shapes()
  5274. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5275. self.shell.init_tcl()
  5276. # delete any selection shape on canvas
  5277. self.delete_selection_shape()
  5278. # delete all FlatCAM objects
  5279. self.collection.delete_all()
  5280. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5281. self.setup_component_editor()
  5282. # Clear project filename
  5283. self.project_filename = None
  5284. # Load the application defaults
  5285. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5286. # Re-fresh project options
  5287. self.on_options_app2project()
  5288. # Init FlatCAMTools
  5289. self.init_tools()
  5290. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5291. if cli is None:
  5292. # we need to go in reverse because once we remove a tab then the index changes
  5293. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5294. # and so on. Therefore the deletion should be done in reverse
  5295. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5296. for index in range(wdg_count, -1, -1):
  5297. try:
  5298. self.ui.plot_tab_area.closeTab(index)
  5299. except Exception as e:
  5300. log.debug("App.on_file_new() --> %s" % str(e))
  5301. # # And then add again the Plot Area
  5302. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5303. self.ui.plot_tab_area.protectTab(0)
  5304. # take the focus of the Notebook on Project Tab.
  5305. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5306. self.set_ui_title(name=_("New Project - Not saved"))
  5307. def obj_properties(self):
  5308. """
  5309. Will launch the object Properties Tool
  5310. :return:
  5311. """
  5312. self.defaults.report_usage("obj_properties()")
  5313. self.properties_tool.run(toggle=False)
  5314. def on_project_context_save(self):
  5315. """
  5316. Wrapper, will save the object function of it's type
  5317. :return:
  5318. """
  5319. obj = self.collection.get_active()
  5320. if type(obj) == GeometryObject:
  5321. self.on_file_exportdxf()
  5322. elif type(obj) == ExcellonObject:
  5323. self.on_file_saveexcellon()
  5324. elif type(obj) == CNCJobObject:
  5325. obj.on_exportgcode_button_click()
  5326. elif type(obj) == GerberObject:
  5327. self.on_file_savegerber()
  5328. elif type(obj) == ScriptObject:
  5329. self.on_file_savescript()
  5330. elif type(obj) == DocumentObject:
  5331. self.on_file_savedocument()
  5332. def obj_move(self):
  5333. """
  5334. Callback for the Move menu entry in various Context Menu's.
  5335. :return:
  5336. """
  5337. self.defaults.report_usage("obj_move()")
  5338. self.move_tool.run(toggle=False)
  5339. def on_fileopengerber(self, signal, name=None):
  5340. """
  5341. File menu callback for opening a Gerber.
  5342. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5343. :param name:
  5344. :return: None
  5345. """
  5346. self.defaults.report_usage("on_fileopengerber")
  5347. App.log.debug("on_fileopengerber()")
  5348. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5349. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5350. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5351. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5352. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5353. "*.mil);;" \
  5354. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5355. "Allegro Files (*.art);;" \
  5356. "Mentor Files (*.pho *.gdo);;" \
  5357. "All Files (*.*)"
  5358. if name is None:
  5359. try:
  5360. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5361. directory=self.get_last_folder(),
  5362. filter=_filter_)
  5363. except TypeError:
  5364. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5365. filenames = [str(filename) for filename in filenames]
  5366. else:
  5367. filenames = [name]
  5368. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5369. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5370. _("Opening Gerber file.")),
  5371. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5372. color=QtGui.QColor("gray"))
  5373. if len(filenames) == 0:
  5374. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5375. else:
  5376. for filename in filenames:
  5377. if filename != '':
  5378. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5379. def on_fileopenexcellon(self, signal, name=None):
  5380. """
  5381. File menu callback for opening an Excellon file.
  5382. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5383. :param name:
  5384. :return: None
  5385. """
  5386. self.defaults.report_usage("on_fileopenexcellon")
  5387. App.log.debug("on_fileopenexcellon()")
  5388. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5389. "All Files (*.*)"
  5390. if name is None:
  5391. try:
  5392. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5393. directory=self.get_last_folder(),
  5394. filter=_filter_)
  5395. except TypeError:
  5396. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5397. filenames = [str(filename) for filename in filenames]
  5398. else:
  5399. filenames = [str(name)]
  5400. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5401. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5402. _("Opening Excellon file.")),
  5403. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5404. color=QtGui.QColor("gray"))
  5405. if len(filenames) == 0:
  5406. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5407. else:
  5408. for filename in filenames:
  5409. if filename != '':
  5410. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5411. def on_fileopengcode(self, signal, name=None):
  5412. """
  5413. File menu call back for opening gcode.
  5414. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5415. :param name:
  5416. :return:
  5417. """
  5418. self.defaults.report_usage("on_fileopengcode")
  5419. App.log.debug("on_fileopengcode()")
  5420. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5421. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5422. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5423. "All Files (*.*)"
  5424. if name is None:
  5425. try:
  5426. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5427. directory=self.get_last_folder(),
  5428. filter=_filter_)
  5429. except TypeError:
  5430. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5431. filenames = [str(filename) for filename in filenames]
  5432. else:
  5433. filenames = [name]
  5434. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5435. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5436. _("Opening G-Code file.")),
  5437. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5438. color=QtGui.QColor("gray"))
  5439. if len(filenames) == 0:
  5440. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5441. else:
  5442. for filename in filenames:
  5443. if filename != '':
  5444. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5445. def on_file_openproject(self, signal):
  5446. """
  5447. File menu callback for opening a project.
  5448. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5449. :return: None
  5450. """
  5451. self.defaults.report_usage("on_file_openproject")
  5452. App.log.debug("on_file_openproject()")
  5453. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5454. try:
  5455. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5456. directory=self.get_last_folder(), filter=_filter_)
  5457. except TypeError:
  5458. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5459. # The Qt methods above will return a QString which can cause problems later.
  5460. # So far json.dump() will fail to serialize it.
  5461. # TODO: Improve the serialization methods and remove this fix.
  5462. filename = str(filename)
  5463. if filename == "":
  5464. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5465. else:
  5466. # self.worker_task.emit({'fcn': self.open_project,
  5467. # 'params': [filename]})
  5468. # The above was failing because open_project() is not
  5469. # thread safe. The new_project()
  5470. self.open_project(filename)
  5471. def on_fileopenhpgl2(self, signal, name=None):
  5472. """
  5473. File menu callback for opening a HPGL2.
  5474. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5475. :param name:
  5476. :return: None
  5477. """
  5478. self.defaults.report_usage("on_fileopenhpgl2")
  5479. App.log.debug("on_fileopenhpgl2()")
  5480. _filter_ = "HPGL2 Files (*.plt);;" \
  5481. "All Files (*.*)"
  5482. if name is None:
  5483. try:
  5484. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5485. directory=self.get_last_folder(),
  5486. filter=_filter_)
  5487. except TypeError:
  5488. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5489. filenames = [str(filename) for filename in filenames]
  5490. else:
  5491. filenames = [name]
  5492. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5493. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5494. _("Opening HPGL2 file.")),
  5495. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5496. color=QtGui.QColor("gray"))
  5497. if len(filenames) == 0:
  5498. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5499. else:
  5500. for filename in filenames:
  5501. if filename != '':
  5502. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5503. def on_file_openconfig(self, signal):
  5504. """
  5505. File menu callback for opening a config file.
  5506. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5507. :return: None
  5508. """
  5509. self.defaults.report_usage("on_file_openconfig")
  5510. App.log.debug("on_file_openconfig()")
  5511. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5512. try:
  5513. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5514. directory=self.data_path, filter=_filter_)
  5515. except TypeError:
  5516. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5517. filter=_filter_)
  5518. if filename == "":
  5519. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5520. else:
  5521. self.open_config_file(filename)
  5522. def on_file_exportsvg(self):
  5523. """
  5524. Callback for menu item File->Export SVG.
  5525. :return: None
  5526. """
  5527. self.defaults.report_usage("on_file_exportsvg")
  5528. App.log.debug("on_file_exportsvg()")
  5529. obj = self.collection.get_active()
  5530. if obj is None:
  5531. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5532. msg = _("Please Select a Geometry object to export")
  5533. msgbox = QtWidgets.QMessageBox()
  5534. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5535. msgbox.setInformativeText(msg)
  5536. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5537. msgbox.setDefaultButton(bt_ok)
  5538. msgbox.exec_()
  5539. return
  5540. # Check for more compatible types and add as required
  5541. if (not isinstance(obj, GeometryObject)
  5542. and not isinstance(obj, GerberObject)
  5543. and not isinstance(obj, CNCJobObject)
  5544. and not isinstance(obj, ExcellonObject)):
  5545. msg = '[ERROR_NOTCL] %s' % \
  5546. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5547. msgbox = QtWidgets.QMessageBox()
  5548. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5549. msgbox.setInformativeText(msg)
  5550. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5551. msgbox.setDefaultButton(bt_ok)
  5552. msgbox.exec_()
  5553. return
  5554. name = obj.options["name"]
  5555. _filter = "SVG File (*.svg);;All Files (*.*)"
  5556. try:
  5557. filename, _f = FCFileSaveDialog.get_saved_filename(
  5558. caption=_("Export SVG"),
  5559. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5560. ext_filter=_filter)
  5561. except TypeError:
  5562. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5563. filename = str(filename)
  5564. if filename == "":
  5565. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5566. return
  5567. else:
  5568. self.export_svg(name, filename)
  5569. if self.defaults["global_open_style"] is False:
  5570. self.file_opened.emit("SVG", filename)
  5571. self.file_saved.emit("SVG", filename)
  5572. def on_file_exportpng(self):
  5573. self.defaults.report_usage("on_file_exportpng")
  5574. App.log.debug("on_file_exportpng()")
  5575. self.date = str(datetime.today()).rpartition('.')[0]
  5576. self.date = ''.join(c for c in self.date if c not in ':-')
  5577. self.date = self.date.replace(' ', '_')
  5578. data = None
  5579. if self.is_legacy is False:
  5580. image = _screenshot(alpha=None)
  5581. data = np.asarray(image)
  5582. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5583. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5584. return
  5585. filter_ = "PNG File (*.png);;All Files (*.*)"
  5586. try:
  5587. filename, _f = FCFileSaveDialog.get_saved_filename(
  5588. caption=_("Export PNG Image"),
  5589. directory=self.get_last_save_folder() + '/png_' + self.date,
  5590. ext_filter=filter_)
  5591. except TypeError:
  5592. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5593. filename = str(filename)
  5594. if filename == "":
  5595. self.inform.emit(_("Cancelled."))
  5596. return
  5597. else:
  5598. if self.is_legacy is False:
  5599. write_png(filename, data)
  5600. else:
  5601. self.plotcanvas.figure.savefig(filename)
  5602. if self.defaults["global_open_style"] is False:
  5603. self.file_opened.emit("png", filename)
  5604. self.file_saved.emit("png", filename)
  5605. def on_file_savegerber(self):
  5606. """
  5607. Callback for menu item in Project context menu.
  5608. :return: None
  5609. """
  5610. self.defaults.report_usage("on_file_savegerber")
  5611. App.log.debug("on_file_savegerber()")
  5612. obj = self.collection.get_active()
  5613. if obj is None:
  5614. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5615. return
  5616. # Check for more compatible types and add as required
  5617. if not isinstance(obj, GerberObject):
  5618. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5619. return
  5620. name = self.collection.get_active().options["name"]
  5621. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5622. try:
  5623. filename, _f = FCFileSaveDialog.get_saved_filename(
  5624. caption="Save Gerber source file",
  5625. directory=self.get_last_save_folder() + '/' + name,
  5626. ext_filter=_filter)
  5627. except TypeError:
  5628. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5629. filename = str(filename)
  5630. if filename == "":
  5631. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5632. return
  5633. else:
  5634. self.save_source_file(name, filename)
  5635. if self.defaults["global_open_style"] is False:
  5636. self.file_opened.emit("Gerber", filename)
  5637. self.file_saved.emit("Gerber", filename)
  5638. def on_file_savescript(self):
  5639. """
  5640. Callback for menu item in Project context menu.
  5641. :return: None
  5642. """
  5643. self.defaults.report_usage("on_file_savescript")
  5644. App.log.debug("on_file_savescript()")
  5645. obj = self.collection.get_active()
  5646. if obj is None:
  5647. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5648. return
  5649. # Check for more compatible types and add as required
  5650. if not isinstance(obj, ScriptObject):
  5651. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5652. return
  5653. name = self.collection.get_active().options["name"]
  5654. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5655. try:
  5656. filename, _f = FCFileSaveDialog.get_saved_filename(
  5657. caption="Save Script source file",
  5658. directory=self.get_last_save_folder() + '/' + name,
  5659. ext_filter=_filter)
  5660. except TypeError:
  5661. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5662. filename = str(filename)
  5663. if filename == "":
  5664. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5665. return
  5666. else:
  5667. self.save_source_file(name, filename)
  5668. if self.defaults["global_open_style"] is False:
  5669. self.file_opened.emit("Script", filename)
  5670. self.file_saved.emit("Script", filename)
  5671. def on_file_savedocument(self):
  5672. """
  5673. Callback for menu item in Project context menu.
  5674. :return: None
  5675. """
  5676. self.defaults.report_usage("on_file_savedocument")
  5677. App.log.debug("on_file_savedocument()")
  5678. obj = self.collection.get_active()
  5679. if obj is None:
  5680. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5681. return
  5682. # Check for more compatible types and add as required
  5683. if not isinstance(obj, ScriptObject):
  5684. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5685. return
  5686. name = self.collection.get_active().options["name"]
  5687. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5688. try:
  5689. filename, _f = FCFileSaveDialog.get_saved_filename(
  5690. caption="Save Document source file",
  5691. directory=self.get_last_save_folder() + '/' + name,
  5692. ext_filter=_filter)
  5693. except TypeError:
  5694. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5695. ext_filter=_filter)
  5696. filename = str(filename)
  5697. if filename == "":
  5698. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5699. return
  5700. else:
  5701. self.save_source_file(name, filename)
  5702. if self.defaults["global_open_style"] is False:
  5703. self.file_opened.emit("Document", filename)
  5704. self.file_saved.emit("Document", filename)
  5705. def on_file_saveexcellon(self):
  5706. """
  5707. Callback for menu item in project context menu.
  5708. :return: None
  5709. """
  5710. self.defaults.report_usage("on_file_saveexcellon")
  5711. App.log.debug("on_file_saveexcellon()")
  5712. obj = self.collection.get_active()
  5713. if obj is None:
  5714. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5715. return
  5716. # Check for more compatible types and add as required
  5717. if not isinstance(obj, ExcellonObject):
  5718. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5719. return
  5720. name = self.collection.get_active().options["name"]
  5721. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5722. try:
  5723. filename, _f = FCFileSaveDialog.get_saved_filename(
  5724. caption=_("Save Excellon source file"),
  5725. directory=self.get_last_save_folder() + '/' + name,
  5726. ext_filter=_filter)
  5727. except TypeError:
  5728. filename, _f = FCFileSaveDialog.get_saved_filename(
  5729. caption=_("Save Excellon source file"), ext_filter=_filter)
  5730. filename = str(filename)
  5731. if filename == "":
  5732. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5733. return
  5734. else:
  5735. self.save_source_file(name, filename)
  5736. if self.defaults["global_open_style"] is False:
  5737. self.file_opened.emit("Excellon", filename)
  5738. self.file_saved.emit("Excellon", filename)
  5739. def on_file_exportexcellon(self):
  5740. """
  5741. Callback for menu item File->Export->Excellon.
  5742. :return: None
  5743. """
  5744. self.defaults.report_usage("on_file_exportexcellon")
  5745. App.log.debug("on_file_exportexcellon()")
  5746. obj = self.collection.get_active()
  5747. if obj is None:
  5748. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5749. return
  5750. # Check for more compatible types and add as required
  5751. if not isinstance(obj, ExcellonObject):
  5752. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5753. return
  5754. name = self.collection.get_active().options["name"]
  5755. _filter = self.defaults["excellon_save_filters"]
  5756. try:
  5757. filename, _f = FCFileSaveDialog.get_saved_filename(
  5758. caption=_("Export Excellon"),
  5759. directory=self.get_last_save_folder() + '/' + name,
  5760. ext_filter=_filter)
  5761. except TypeError:
  5762. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5763. filename = str(filename)
  5764. if filename == "":
  5765. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5766. return
  5767. else:
  5768. used_extension = filename.rpartition('.')[2]
  5769. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5770. self.export_excellon(name, filename)
  5771. if self.defaults["global_open_style"] is False:
  5772. self.file_opened.emit("Excellon", filename)
  5773. self.file_saved.emit("Excellon", filename)
  5774. def on_file_exportgerber(self):
  5775. """
  5776. Callback for menu item File->Export->Gerber.
  5777. :return: None
  5778. """
  5779. self.defaults.report_usage("on_file_exportgerber")
  5780. App.log.debug("on_file_exportgerber()")
  5781. obj = self.collection.get_active()
  5782. if obj is None:
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5784. return
  5785. # Check for more compatible types and add as required
  5786. if not isinstance(obj, GerberObject):
  5787. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5788. return
  5789. name = self.collection.get_active().options["name"]
  5790. _filter_ = self.defaults['gerber_save_filters']
  5791. try:
  5792. filename, _f = FCFileSaveDialog.get_saved_filename(
  5793. caption=_("Export Gerber"),
  5794. directory=self.get_last_save_folder() + '/' + name,
  5795. ext_filter=_filter_)
  5796. except TypeError:
  5797. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5798. filename = str(filename)
  5799. if filename == "":
  5800. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5801. return
  5802. else:
  5803. used_extension = filename.rpartition('.')[2]
  5804. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5805. self.export_gerber(name, filename)
  5806. if self.defaults["global_open_style"] is False:
  5807. self.file_opened.emit("Gerber", filename)
  5808. self.file_saved.emit("Gerber", filename)
  5809. def on_file_exportdxf(self):
  5810. """
  5811. Callback for menu item File->Export DXF.
  5812. :return: None
  5813. """
  5814. self.defaults.report_usage("on_file_exportdxf")
  5815. App.log.debug("on_file_exportdxf()")
  5816. obj = self.collection.get_active()
  5817. if obj is None:
  5818. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5819. msg = _("Please Select a Geometry object to export")
  5820. msgbox = QtWidgets.QMessageBox()
  5821. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5822. msgbox.setInformativeText(msg)
  5823. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5824. msgbox.setDefaultButton(bt_ok)
  5825. msgbox.exec_()
  5826. return
  5827. # Check for more compatible types and add as required
  5828. if not isinstance(obj, GeometryObject):
  5829. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5830. msgbox = QtWidgets.QMessageBox()
  5831. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5832. msgbox.setInformativeText(msg)
  5833. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5834. msgbox.setDefaultButton(bt_ok)
  5835. msgbox.exec_()
  5836. return
  5837. name = self.collection.get_active().options["name"]
  5838. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5839. try:
  5840. filename, _f = FCFileSaveDialog.get_saved_filename(
  5841. caption=_("Export DXF"),
  5842. directory=self.get_last_save_folder() + '/' + name,
  5843. ext_filter=_filter_)
  5844. except TypeError:
  5845. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  5846. filename = str(filename)
  5847. if filename == "":
  5848. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5849. return
  5850. else:
  5851. self.export_dxf(name, filename)
  5852. if self.defaults["global_open_style"] is False:
  5853. self.file_opened.emit("DXF", filename)
  5854. self.file_saved.emit("DXF", filename)
  5855. def on_file_importsvg(self, type_of_obj):
  5856. """
  5857. Callback for menu item File->Import SVG.
  5858. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5859. :type type_of_obj: str
  5860. :return: None
  5861. """
  5862. self.defaults.report_usage("on_file_importsvg")
  5863. App.log.debug("on_file_importsvg()")
  5864. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5865. try:
  5866. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5867. directory=self.get_last_folder(), filter=_filter_)
  5868. except TypeError:
  5869. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5870. filter=_filter_)
  5871. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5872. type_of_obj = "geometry"
  5873. filenames = [str(filename) for filename in filenames]
  5874. if len(filenames) == 0:
  5875. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5876. else:
  5877. for filename in filenames:
  5878. if filename != '':
  5879. self.worker_task.emit({'fcn': self.import_svg,
  5880. 'params': [filename, type_of_obj]})
  5881. def on_file_importdxf(self, type_of_obj):
  5882. """
  5883. Callback for menu item File->Import DXF.
  5884. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5885. :type type_of_obj: str
  5886. :return: None
  5887. """
  5888. self.defaults.report_usage("on_file_importdxf")
  5889. App.log.debug("on_file_importdxf()")
  5890. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5891. try:
  5892. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5893. directory=self.get_last_folder(),
  5894. filter=_filter_)
  5895. except TypeError:
  5896. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5897. filter=_filter_)
  5898. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5899. type_of_obj = "geometry"
  5900. filenames = [str(filename) for filename in filenames]
  5901. if len(filenames) == 0:
  5902. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5903. else:
  5904. for filename in filenames:
  5905. if filename != '':
  5906. self.worker_task.emit({'fcn': self.import_dxf,
  5907. 'params': [filename, type_of_obj]})
  5908. # ###############################################################################################################
  5909. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5910. # ###############################################################################################################
  5911. def init_code_editor(self, name):
  5912. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5913. # add the tab if it was closed
  5914. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5915. self.text_editor_tab.setObjectName('text_editor_tab')
  5916. # delete the absolute and relative position and messages in the infobar
  5917. self.ui.position_label.setText("")
  5918. # self.ui.rel_position_label.setText("")
  5919. # first clear previous text in text editor (if any)
  5920. self.text_editor_tab.code_editor.clear()
  5921. self.text_editor_tab.code_editor.setReadOnly(False)
  5922. self.toggle_codeeditor = True
  5923. self.text_editor_tab.code_editor.completer_enable = False
  5924. self.text_editor_tab.buttonRun.hide()
  5925. # make sure to keep a reference to the code editor
  5926. self.reference_code_editor = self.text_editor_tab.code_editor
  5927. # Switch plot_area to CNCJob tab
  5928. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5929. def on_view_source(self):
  5930. """
  5931. Called when the user wants to see the source file of the selected object
  5932. :return:
  5933. """
  5934. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5935. self.proc_container.view.set_busy(_("Loading..."))
  5936. try:
  5937. obj = self.collection.get_active()
  5938. except Exception as e:
  5939. log.debug("App.on_view_source() --> %s" % str(e))
  5940. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5941. return 'fail'
  5942. if obj is None:
  5943. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5944. return 'fail'
  5945. flt = "All Files (*.*)"
  5946. if obj.kind == 'gerber':
  5947. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5948. elif obj.kind == 'excellon':
  5949. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5950. elif obj.kind == 'cncjob':
  5951. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5952. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5953. # add the tab if it was closed
  5954. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5955. self.source_editor_tab.setObjectName('source_editor_tab')
  5956. # delete the absolute and relative position and messages in the infobar
  5957. self.ui.position_label.setText("")
  5958. # self.ui.rel_position_label.setText("")
  5959. # first clear previous text in text editor (if any)
  5960. self.source_editor_tab.code_editor.clear()
  5961. self.source_editor_tab.code_editor.setReadOnly(False)
  5962. self.source_editor_tab.code_editor.completer_enable = False
  5963. self.source_editor_tab.buttonRun.hide()
  5964. # Switch plot_area to CNCJob tab
  5965. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5966. try:
  5967. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5968. except TypeError:
  5969. pass
  5970. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5971. try:
  5972. self.source_editor_tab.buttonSave.clicked.disconnect()
  5973. except TypeError:
  5974. pass
  5975. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5976. # then append the text from GCode to the text editor
  5977. if obj.kind == 'cncjob':
  5978. try:
  5979. file = obj.export_gcode(
  5980. preamble=self.defaults["cncjob_prepend"],
  5981. postamble=self.defaults["cncjob_append"],
  5982. to_file=True)
  5983. if file == 'fail':
  5984. return 'fail'
  5985. except AttributeError:
  5986. self.inform.emit('[WARNING_NOTCL] %s' %
  5987. _("There is no selected object for which to see it's source file code."))
  5988. return 'fail'
  5989. else:
  5990. try:
  5991. file = StringIO(obj.source_file)
  5992. except (AttributeError, TypeError):
  5993. self.inform.emit('[WARNING_NOTCL] %s' %
  5994. _("There is no selected object for which to see it's source file code."))
  5995. return 'fail'
  5996. self.source_editor_tab.t_frame.hide()
  5997. try:
  5998. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  5999. # for line in file:
  6000. # QtWidgets.QApplication.processEvents()
  6001. # proc_line = str(line).strip('\n')
  6002. # self.source_editor_tab.code_editor.append(proc_line)
  6003. except Exception as e:
  6004. log.debug('App.on_view_source() -->%s' % str(e))
  6005. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6006. return
  6007. self.source_editor_tab.handleTextChanged()
  6008. self.source_editor_tab.t_frame.show()
  6009. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6010. self.proc_container.view.set_idle()
  6011. # self.ui.show()
  6012. def on_toggle_code_editor(self):
  6013. self.defaults.report_usage("on_toggle_code_editor()")
  6014. if self.toggle_codeeditor is False:
  6015. self.init_code_editor(name=_("Code Editor"))
  6016. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6017. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6018. self.text_editor_tab.buttonSave.clicked.disconnect()
  6019. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6020. else:
  6021. for idx in range(self.ui.plot_tab_area.count()):
  6022. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6023. self.ui.plot_tab_area.closeTab(idx)
  6024. break
  6025. self.toggle_codeeditor = False
  6026. def on_code_editor_close(self):
  6027. self.toggle_codeeditor = False
  6028. def goto_text_line(self):
  6029. """
  6030. Will scroll a text to the specified text line.
  6031. :return: None
  6032. """
  6033. dia_box = Dialog_box(title=_("Go to Line ..."),
  6034. label=_("Line:"),
  6035. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6036. initial_text='')
  6037. try:
  6038. line = int(dia_box.location) - 1
  6039. except (ValueError, TypeError):
  6040. line = 0
  6041. if dia_box.ok:
  6042. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6043. # at the top of the window
  6044. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6045. # get the document() of the TextEditor
  6046. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6047. # create a Text Cursor based on the searched line
  6048. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6049. # set cursor of the code editor with the cursor at the searcehd line
  6050. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6051. def on_filenewscript(self, silent=False):
  6052. """
  6053. Will create a new script file and open it in the Code Editor
  6054. :param silent: if True will not display status messages
  6055. :return: None
  6056. """
  6057. if silent is False:
  6058. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6059. # delete the absolute and relative position and messages in the infobar
  6060. self.ui.position_label.setText("")
  6061. # self.ui.rel_position_label.setText("")
  6062. self.app_obj.new_script_object()
  6063. # script_text = script_obj.source_file
  6064. #
  6065. # self.proc_container.view.set_busy(_("Loading..."))
  6066. # script_obj.script_editor_tab.t_frame.hide()
  6067. #
  6068. # script_obj.script_editor_tab.t_frame.show()
  6069. # self.proc_container.view.set_idle()
  6070. def on_fileopenscript(self, name=None, silent=False):
  6071. """
  6072. Will open a Tcl script file into the Code Editor
  6073. :param silent: if True will not display status messages
  6074. :param name: name of a Tcl script file to open
  6075. :return: None
  6076. """
  6077. self.defaults.report_usage("on_fileopenscript")
  6078. App.log.debug("on_fileopenscript()")
  6079. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6080. "All Files (*.*)"
  6081. if name:
  6082. filenames = [name]
  6083. else:
  6084. try:
  6085. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6086. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6087. except TypeError:
  6088. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6089. if len(filenames) == 0:
  6090. if silent is False:
  6091. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6092. else:
  6093. for filename in filenames:
  6094. if filename != '':
  6095. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6096. def on_fileopenscript_example(self, name=None, silent=False):
  6097. """
  6098. Will open a Tcl script file into the Code Editor
  6099. :param silent: if True will not display status messages
  6100. :param name: name of a Tcl script file to open
  6101. :return:
  6102. """
  6103. self.defaults.report_usage("on_fileopenscript_example")
  6104. log.debug("on_fileopenscript_example()")
  6105. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6106. "All Files (*.*)"
  6107. # test if the app was frozen and choose the path for the configuration file
  6108. if getattr(sys, "frozen", False) is True:
  6109. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6110. else:
  6111. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6112. if name:
  6113. filenames = [name]
  6114. else:
  6115. try:
  6116. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6117. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6118. except TypeError:
  6119. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6120. if len(filenames) == 0:
  6121. if silent is False:
  6122. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6123. else:
  6124. for filename in filenames:
  6125. if filename != '':
  6126. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6127. def on_filerunscript(self, name=None, silent=False):
  6128. """
  6129. File menu callback for loading and running a TCL script.
  6130. :param silent: if True will not display status messages
  6131. :param name: name of a Tcl script file to be run by FlatCAM
  6132. :return: None
  6133. """
  6134. self.defaults.report_usage("on_filerunscript")
  6135. App.log.debug("on_file_runscript()")
  6136. if name:
  6137. filename = name
  6138. if self.cmd_line_headless != 1:
  6139. self.splash.showMessage('%s: %ssec\n%s' %
  6140. (_("Canvas initialization started.\n"
  6141. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6142. _("Executing ScriptObject file.")
  6143. ),
  6144. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6145. color=QtGui.QColor("gray"))
  6146. else:
  6147. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6148. "All Files (*.*)"
  6149. try:
  6150. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6151. directory=self.get_last_folder(), filter=_filter_)
  6152. except TypeError:
  6153. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6154. # The Qt methods above will return a QString which can cause problems later.
  6155. # So far json.dump() will fail to serialize it.
  6156. filename = str(filename)
  6157. if filename == "":
  6158. if silent is False:
  6159. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6160. else:
  6161. if self.cmd_line_headless != 1:
  6162. if self.ui.shell_dock.isHidden():
  6163. self.ui.shell_dock.show()
  6164. try:
  6165. with open(filename, "r") as tcl_script:
  6166. cmd_line_shellfile_content = tcl_script.read()
  6167. if self.cmd_line_headless != 1:
  6168. self.shell.exec_command(cmd_line_shellfile_content)
  6169. else:
  6170. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6171. if silent is False:
  6172. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6173. except Exception as e:
  6174. log.debug("App.on_filerunscript() -> %s" % str(e))
  6175. sys.exit(2)
  6176. def on_file_saveproject(self, silent=False):
  6177. """
  6178. Callback for menu item File->Save Project. Saves the project to
  6179. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6180. if set to None. The project is saved by calling ``self.save_project()``.
  6181. :param silent: if True will not display status messages
  6182. :return: None
  6183. """
  6184. self.defaults.report_usage("on_file_saveproject")
  6185. if self.project_filename is None:
  6186. self.on_file_saveprojectas()
  6187. else:
  6188. self.worker_task.emit({'fcn': self.save_project,
  6189. 'params': [self.project_filename, silent]})
  6190. if self.defaults["global_open_style"] is False:
  6191. self.file_opened.emit("project", self.project_filename)
  6192. self.file_saved.emit("project", self.project_filename)
  6193. self.set_ui_title(name=self.project_filename)
  6194. self.should_we_save = False
  6195. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6196. """
  6197. Callback for menu item File->Save Project As... Opens a file
  6198. chooser and saves the project to the given file via
  6199. ``self.save_project()``.
  6200. :param make_copy if to be create a copy of the project; boolean
  6201. :param use_thread: if to be run in a separate thread; boolean
  6202. :param quit_action: if to be followed by quiting the application; boolean
  6203. :return: None
  6204. """
  6205. self.defaults.report_usage("on_file_saveprojectas")
  6206. self.date = str(datetime.today()).rpartition('.')[0]
  6207. self.date = ''.join(c for c in self.date if c not in ':-')
  6208. self.date = self.date.replace(' ', '_')
  6209. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6210. try:
  6211. filename, _f = FCFileSaveDialog.get_saved_filename(
  6212. caption=_("Save Project As ..."),
  6213. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6214. proj=_("Project")),
  6215. ext_filter=filter_
  6216. )
  6217. except TypeError:
  6218. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6219. filename = str(filename)
  6220. if filename == '':
  6221. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6222. return
  6223. if use_thread is True:
  6224. self.worker_task.emit({'fcn': self.save_project,
  6225. 'params': [filename, quit_action]})
  6226. else:
  6227. self.save_project(filename, quit_action)
  6228. # self.save_project(filename)
  6229. if self.defaults["global_open_style"] is False:
  6230. self.file_opened.emit("project", filename)
  6231. self.file_saved.emit("project", filename)
  6232. if not make_copy:
  6233. self.project_filename = filename
  6234. self.set_ui_title(name=self.project_filename)
  6235. self.should_we_save = False
  6236. def on_file_save_objects_pdf(self, use_thread=True):
  6237. self.date = str(datetime.today()).rpartition('.')[0]
  6238. self.date = ''.join(c for c in self.date if c not in ':-')
  6239. self.date = self.date.replace(' ', '_')
  6240. try:
  6241. obj_selection = self.collection.get_selected()
  6242. if len(obj_selection) == 1:
  6243. obj_name = str(obj_selection[0].options['name'])
  6244. else:
  6245. obj_name = _("FlatCAM objects print")
  6246. except AttributeError as err:
  6247. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6248. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6249. return
  6250. if not obj_selection:
  6251. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6252. return
  6253. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6254. try:
  6255. filename, _f = FCFileSaveDialog.get_saved_filename(
  6256. caption=_("Save Object as PDF ..."),
  6257. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6258. obj_name=obj_name,
  6259. date=self.date),
  6260. ext_filter=filter_
  6261. )
  6262. except TypeError:
  6263. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6264. filename = str(filename)
  6265. if filename == '':
  6266. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6267. return
  6268. if use_thread is True:
  6269. self.proc_container.new(_("Printing PDF ... Please wait."))
  6270. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6271. else:
  6272. self.save_pdf(filename, obj_selection)
  6273. # self.save_project(filename)
  6274. if self.defaults["global_open_style"] is False:
  6275. self.file_opened.emit("pdf", filename)
  6276. self.file_saved.emit("pdf", filename)
  6277. def save_pdf(self, file_name, obj_selection):
  6278. p_size = self.defaults['global_workspaceT']
  6279. orientation = self.defaults['global_workspace_orientation']
  6280. color = 'black'
  6281. transparency_level = 1.0
  6282. self.pagesize = {}
  6283. self.pagesize.update(
  6284. {
  6285. 'Bounds': None,
  6286. 'A0': (841 * mm, 1189 * mm),
  6287. 'A1': (594 * mm, 841 * mm),
  6288. 'A2': (420 * mm, 594 * mm),
  6289. 'A3': (297 * mm, 420 * mm),
  6290. 'A4': (210 * mm, 297 * mm),
  6291. 'A5': (148 * mm, 210 * mm),
  6292. 'A6': (105 * mm, 148 * mm),
  6293. 'A7': (74 * mm, 105 * mm),
  6294. 'A8': (52 * mm, 74 * mm),
  6295. 'A9': (37 * mm, 52 * mm),
  6296. 'A10': (26 * mm, 37 * mm),
  6297. 'B0': (1000 * mm, 1414 * mm),
  6298. 'B1': (707 * mm, 1000 * mm),
  6299. 'B2': (500 * mm, 707 * mm),
  6300. 'B3': (353 * mm, 500 * mm),
  6301. 'B4': (250 * mm, 353 * mm),
  6302. 'B5': (176 * mm, 250 * mm),
  6303. 'B6': (125 * mm, 176 * mm),
  6304. 'B7': (88 * mm, 125 * mm),
  6305. 'B8': (62 * mm, 88 * mm),
  6306. 'B9': (44 * mm, 62 * mm),
  6307. 'B10': (31 * mm, 44 * mm),
  6308. 'C0': (917 * mm, 1297 * mm),
  6309. 'C1': (648 * mm, 917 * mm),
  6310. 'C2': (458 * mm, 648 * mm),
  6311. 'C3': (324 * mm, 458 * mm),
  6312. 'C4': (229 * mm, 324 * mm),
  6313. 'C5': (162 * mm, 229 * mm),
  6314. 'C6': (114 * mm, 162 * mm),
  6315. 'C7': (81 * mm, 114 * mm),
  6316. 'C8': (57 * mm, 81 * mm),
  6317. 'C9': (40 * mm, 57 * mm),
  6318. 'C10': (28 * mm, 40 * mm),
  6319. # American paper sizes
  6320. 'LETTER': (8.5 * inch, 11 * inch),
  6321. 'LEGAL': (8.5 * inch, 14 * inch),
  6322. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6323. # From https://en.wikipedia.org/wiki/Paper_size
  6324. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6325. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6326. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6327. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6328. 'LEDGER': (17 * inch, 11 * inch),
  6329. }
  6330. )
  6331. exported_svg = []
  6332. for obj in obj_selection:
  6333. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6334. scale_factor_x=None, scale_factor_y=None,
  6335. skew_factor_x=None, skew_factor_y=None,
  6336. mirror=None)
  6337. if obj.kind.lower() == 'gerber':
  6338. # color = self.defaults["gerber_plot_fill"][:-2]
  6339. color = obj.fill_color[:-2]
  6340. elif obj.kind.lower() == 'excellon':
  6341. color = '#C40000'
  6342. elif obj.kind.lower() == 'geometry':
  6343. color = self.defaults["global_draw_color"]
  6344. # Change the attributes of the exported SVG
  6345. # We don't need stroke-width
  6346. # We set opacity to maximum
  6347. # We set the colour to WHITE
  6348. root = ET.fromstring(svg_obj)
  6349. for child in root:
  6350. child.set('fill', str(color))
  6351. child.set('opacity', str(transparency_level))
  6352. child.set('stroke', str(color))
  6353. exported_svg.append(ET.tostring(root))
  6354. xmin = Inf
  6355. ymin = Inf
  6356. xmax = -Inf
  6357. ymax = -Inf
  6358. for obj in obj_selection:
  6359. try:
  6360. gxmin, gymin, gxmax, gymax = obj.bounds()
  6361. xmin = min([xmin, gxmin])
  6362. ymin = min([ymin, gymin])
  6363. xmax = max([xmax, gxmax])
  6364. ymax = max([ymax, gymax])
  6365. except Exception as e:
  6366. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6367. # Determine bounding area for svg export
  6368. bounds = [xmin, ymin, xmax, ymax]
  6369. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6370. # This contain the measure units
  6371. uom = obj_selection[0].units.lower()
  6372. # Define a boundary around SVG of about 1.0mm (~39mils)
  6373. if uom in "mm":
  6374. boundary = 1.0
  6375. else:
  6376. boundary = 0.0393701
  6377. # Convert everything to strings for use in the xml doc
  6378. svgwidth = str(size[0] + (2 * boundary))
  6379. svgheight = str(size[1] + (2 * boundary))
  6380. minx = str(bounds[0] - boundary)
  6381. miny = str(bounds[1] + boundary + size[1])
  6382. # Add a SVG Header and footer to the svg output from shapely
  6383. # The transform flips the Y Axis so that everything renders
  6384. # properly within svg apps such as inkscape
  6385. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6386. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6387. svg_header += 'width="' + svgwidth + uom + '" '
  6388. svg_header += 'height="' + svgheight + uom + '" '
  6389. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6390. svg_header += '>'
  6391. svg_header += '<g transform="scale(1,-1)">'
  6392. svg_footer = '</g> </svg>'
  6393. svg_elem = str(svg_header)
  6394. for svg_item in exported_svg:
  6395. svg_elem += str(svg_item)
  6396. svg_elem += str(svg_footer)
  6397. # Parse the xml through a xml parser just to add line feeds
  6398. # and to make it look more pretty for the output
  6399. doc = parse_xml_string(svg_elem)
  6400. doc_final = doc.toprettyxml()
  6401. try:
  6402. if self.defaults['units'].upper() == 'IN':
  6403. unit = inch
  6404. else:
  6405. unit = mm
  6406. doc_final = StringIO(doc_final)
  6407. drawing = svg2rlg(doc_final)
  6408. if p_size == 'Bounds':
  6409. renderPDF.drawToFile(drawing, file_name)
  6410. else:
  6411. if orientation == 'p':
  6412. page_size = portrait(self.pagesize[p_size])
  6413. else:
  6414. page_size = landscape(self.pagesize[p_size])
  6415. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6416. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6417. renderPDF.draw(drawing, my_canvas, 0, 0)
  6418. my_canvas.save()
  6419. except Exception as e:
  6420. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6421. return 'fail'
  6422. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6423. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6424. """
  6425. Exports a Geometry Object to an SVG file.
  6426. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6427. :param filename: Path to the SVG file to save to.
  6428. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6429. :return:
  6430. """
  6431. self.defaults.report_usage("export_svg()")
  6432. if filename is None:
  6433. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6434. is not None else self.defaults["global_last_folder"]
  6435. self.log.debug("export_svg()")
  6436. try:
  6437. obj = self.collection.get_by_name(str(obj_name))
  6438. except Exception:
  6439. # TODO: The return behavior has not been established... should raise exception?
  6440. return "Could not retrieve object: %s" % obj_name
  6441. with self.proc_container.new(_("Exporting SVG")) as proc:
  6442. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6443. # Determine bounding area for svg export
  6444. bounds = obj.bounds()
  6445. size = obj.size()
  6446. # Convert everything to strings for use in the xml doc
  6447. svgwidth = str(size[0])
  6448. svgheight = str(size[1])
  6449. minx = str(bounds[0])
  6450. miny = str(bounds[1] - size[1])
  6451. uom = obj.units.lower()
  6452. # Add a SVG Header and footer to the svg output from shapely
  6453. # The transform flips the Y Axis so that everything renders
  6454. # properly within svg apps such as inkscape
  6455. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6456. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6457. svg_header += 'width="' + svgwidth + uom + '" '
  6458. svg_header += 'height="' + svgheight + uom + '" '
  6459. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6460. svg_header += '<g transform="scale(1,-1)">'
  6461. svg_footer = '</g> </svg>'
  6462. svg_elem = svg_header + exported_svg + svg_footer
  6463. # Parse the xml through a xml parser just to add line feeds
  6464. # and to make it look more pretty for the output
  6465. svgcode = parse_xml_string(svg_elem)
  6466. svgcode = svgcode.toprettyxml()
  6467. try:
  6468. with open(filename, 'w') as fp:
  6469. fp.write(svgcode)
  6470. except PermissionError:
  6471. self.inform.emit('[WARNING] %s' %
  6472. _("Permission denied, saving not possible.\n"
  6473. "Most likely another app is holding the file open and not accessible."))
  6474. return 'fail'
  6475. if self.defaults["global_open_style"] is False:
  6476. self.file_opened.emit("SVG", filename)
  6477. self.file_saved.emit("SVG", filename)
  6478. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6479. def save_source_file(self, obj_name, filename, use_thread=True):
  6480. """
  6481. Exports a FlatCAM Object to an Gerber/Excellon file.
  6482. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6483. :param filename: Path to the Gerber file to save to.
  6484. :param use_thread: if to be run in a separate thread
  6485. :return:
  6486. """
  6487. self.defaults.report_usage("save source file()")
  6488. if filename is None:
  6489. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6490. is not None else self.defaults["global_last_folder"]
  6491. self.log.debug("save source file()")
  6492. obj = self.collection.get_by_name(obj_name)
  6493. file_string = StringIO(obj.source_file)
  6494. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6495. if file_string.getvalue() == '':
  6496. self.inform.emit('[ERROR_NOTCL] %s' %
  6497. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6498. return 'fail'
  6499. try:
  6500. with open(filename, 'w') as file:
  6501. file.writelines('G04*\n')
  6502. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6503. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6504. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6505. file.writelines('G04 Created on : %s*\n' % time_string)
  6506. for line in file_string:
  6507. file.writelines(line)
  6508. except PermissionError:
  6509. self.inform.emit('[WARNING] %s' %
  6510. _("Permission denied, saving not possible.\n"
  6511. "Most likely another app is holding the file open and not accessible."))
  6512. return 'fail'
  6513. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6514. """
  6515. Exports a Excellon Object to an Excellon file.
  6516. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6517. :param filename: Path to the Excellon file to save to.
  6518. :param local_use:
  6519. :param use_thread: if to be run in a separate thread
  6520. :return:
  6521. """
  6522. self.defaults.report_usage("export_excellon()")
  6523. if filename is None:
  6524. if self.defaults["global_last_save_folder"]:
  6525. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6526. else:
  6527. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6528. self.log.debug("export_excellon()")
  6529. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6530. self.defaults["excellon_exp_decimals"]
  6531. )
  6532. if local_use is None:
  6533. try:
  6534. obj = self.collection.get_by_name(str(obj_name))
  6535. except Exception:
  6536. return "Could not retrieve object: %s" % obj_name
  6537. else:
  6538. obj = local_use
  6539. if not isinstance(obj, ExcellonObject):
  6540. self.inform.emit('[ERROR_NOTCL] %s' %
  6541. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6542. return
  6543. # updated units
  6544. eunits = self.defaults["excellon_exp_units"]
  6545. ewhole = self.defaults["excellon_exp_integer"]
  6546. efract = self.defaults["excellon_exp_decimals"]
  6547. ezeros = self.defaults["excellon_exp_zeros"]
  6548. eformat = self.defaults["excellon_exp_format"]
  6549. slot_type = self.defaults["excellon_exp_slot_type"]
  6550. fc_units = self.defaults['units'].upper()
  6551. if fc_units == 'MM':
  6552. factor = 1 if eunits == 'METRIC' else 0.03937
  6553. else:
  6554. factor = 25.4 if eunits == 'METRIC' else 1
  6555. def make_excellon():
  6556. try:
  6557. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6558. header = 'M48\n'
  6559. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6560. (str(self.version), str(self.version_date))
  6561. header += ';Filename: %s' % str(obj_name) + '\n'
  6562. header += ';Created on : %s' % time_str + '\n'
  6563. if eformat == 'dec':
  6564. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6565. header += eunits + '\n'
  6566. for tool in obj.tools:
  6567. if eunits == 'METRIC':
  6568. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6569. tool=str(tool),
  6570. dec=2)
  6571. else:
  6572. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6573. tool=str(tool),
  6574. dec=4)
  6575. else:
  6576. if ezeros == 'LZ':
  6577. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6578. form='ndec', e_zeros='LZ', factor=factor,
  6579. slot_type=slot_type)
  6580. header += '%s,%s\n' % (eunits, 'LZ')
  6581. header += format_exc
  6582. for tool in obj.tools:
  6583. if eunits == 'METRIC':
  6584. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6585. tool=str(tool),
  6586. dec=2)
  6587. else:
  6588. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6589. tool=str(tool),
  6590. dec=4)
  6591. else:
  6592. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6593. form='ndec', e_zeros='TZ', factor=factor,
  6594. slot_type=slot_type)
  6595. header += '%s,%s\n' % (eunits, 'TZ')
  6596. header += format_exc
  6597. for tool in obj.tools:
  6598. if eunits == 'METRIC':
  6599. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6600. tool=str(tool),
  6601. dec=2)
  6602. else:
  6603. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6604. tool=str(tool),
  6605. dec=4)
  6606. header += '%\n'
  6607. footer = 'M30\n'
  6608. exported_excellon = header
  6609. exported_excellon += excellon_code
  6610. exported_excellon += footer
  6611. if local_use is None:
  6612. try:
  6613. with open(filename, 'w') as fp:
  6614. fp.write(exported_excellon)
  6615. except PermissionError:
  6616. self.inform.emit('[WARNING] %s' %
  6617. _("Permission denied, saving not possible.\n"
  6618. "Most likely another app is holding the file open and not accessible."))
  6619. return 'fail'
  6620. if self.defaults["global_open_style"] is False:
  6621. self.file_opened.emit("Excellon", filename)
  6622. self.file_saved.emit("Excellon", filename)
  6623. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6624. else:
  6625. return exported_excellon
  6626. except Exception as e:
  6627. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6628. return 'fail'
  6629. if use_thread is True:
  6630. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6631. def job_thread_exc(app_obj):
  6632. ret = make_excellon()
  6633. if ret == 'fail':
  6634. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6635. return
  6636. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6637. else:
  6638. eret = make_excellon()
  6639. if eret == 'fail':
  6640. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6641. return 'fail'
  6642. if local_use is not None:
  6643. return eret
  6644. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6645. """
  6646. Exports a Gerber Object to an Gerber file.
  6647. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6648. :param filename: Path to the Gerber file to save to.
  6649. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6650. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6651. :param use_thread: if to be run in a separate thread
  6652. :return:
  6653. """
  6654. self.defaults.report_usage("export_gerber()")
  6655. if filename is None:
  6656. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6657. is not None else self.defaults["global_last_folder"]
  6658. self.log.debug("export_gerber()")
  6659. if local_use is None:
  6660. try:
  6661. obj = self.collection.get_by_name(str(obj_name))
  6662. except Exception:
  6663. return "Could not retrieve object: %s" % obj_name
  6664. else:
  6665. obj = local_use
  6666. # updated units
  6667. gunits = self.defaults["gerber_exp_units"]
  6668. gwhole = self.defaults["gerber_exp_integer"]
  6669. gfract = self.defaults["gerber_exp_decimals"]
  6670. gzeros = self.defaults["gerber_exp_zeros"]
  6671. fc_units = self.defaults['units'].upper()
  6672. if fc_units == 'MM':
  6673. factor = 1 if gunits == 'MM' else 0.03937
  6674. else:
  6675. factor = 25.4 if gunits == 'MM' else 1
  6676. def make_gerber():
  6677. try:
  6678. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6679. header = 'G04*\n'
  6680. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6681. (str(self.version), str(self.version_date))
  6682. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6683. header += 'G04 Created on : %s*' % time_str + '\n'
  6684. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6685. header += "%MO{units}*%\n".format(units=gunits)
  6686. for apid in obj.apertures:
  6687. if obj.apertures[apid]['type'] == 'C':
  6688. header += "%ADD{apid}{type},{size}*%\n".format(
  6689. apid=str(apid),
  6690. type='C',
  6691. size=(factor * obj.apertures[apid]['size'])
  6692. )
  6693. elif obj.apertures[apid]['type'] == 'R':
  6694. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6695. apid=str(apid),
  6696. type='R',
  6697. width=(factor * obj.apertures[apid]['width']),
  6698. height=(factor * obj.apertures[apid]['height'])
  6699. )
  6700. elif obj.apertures[apid]['type'] == 'O':
  6701. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6702. apid=str(apid),
  6703. type='O',
  6704. width=(factor * obj.apertures[apid]['width']),
  6705. height=(factor * obj.apertures[apid]['height'])
  6706. )
  6707. header += '\n'
  6708. # obsolete units but some software may need it
  6709. if gunits == 'IN':
  6710. header += 'G70*\n'
  6711. else:
  6712. header += 'G71*\n'
  6713. # Absolute Mode
  6714. header += 'G90*\n'
  6715. header += 'G01*\n'
  6716. # positive polarity
  6717. header += '%LPD*%\n'
  6718. footer = 'M02*\n'
  6719. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6720. exported_gerber = header
  6721. exported_gerber += gerber_code
  6722. exported_gerber += footer
  6723. if local_use is None:
  6724. try:
  6725. with open(filename, 'w') as fp:
  6726. fp.write(exported_gerber)
  6727. except PermissionError:
  6728. self.inform.emit('[WARNING] %s' %
  6729. _("Permission denied, saving not possible.\n"
  6730. "Most likely another app is holding the file open and not accessible."))
  6731. return 'fail'
  6732. if self.defaults["global_open_style"] is False:
  6733. self.file_opened.emit("Gerber", filename)
  6734. self.file_saved.emit("Gerber", filename)
  6735. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6736. else:
  6737. return exported_gerber
  6738. except Exception as e:
  6739. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6740. return 'fail'
  6741. if use_thread is True:
  6742. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6743. def job_thread_grb(app_obj):
  6744. ret = make_gerber()
  6745. if ret == 'fail':
  6746. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6747. return
  6748. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6749. else:
  6750. gret = make_gerber()
  6751. if gret == 'fail':
  6752. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6753. return 'fail'
  6754. if local_use is not None:
  6755. return gret
  6756. def export_dxf(self, obj_name, filename, use_thread=True):
  6757. """
  6758. Exports a Geometry Object to an DXF file.
  6759. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6760. :param filename: Path to the DXF file to save to.
  6761. :param use_thread: if to be run in a separate thread
  6762. :return:
  6763. """
  6764. self.defaults.report_usage("export_dxf()")
  6765. if filename is None:
  6766. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6767. is not None else self.defaults["global_last_folder"]
  6768. self.log.debug("export_dxf()")
  6769. try:
  6770. obj = self.collection.get_by_name(str(obj_name))
  6771. except Exception:
  6772. # TODO: The return behavior has not been established... should raise exception?
  6773. return "Could not retrieve object: %s" % obj_name
  6774. def make_dxf():
  6775. try:
  6776. dxf_code = obj.export_dxf()
  6777. dxf_code.saveas(filename)
  6778. if self.defaults["global_open_style"] is False:
  6779. self.file_opened.emit("DXF", filename)
  6780. self.file_saved.emit("DXF", filename)
  6781. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6782. except Exception:
  6783. return 'fail'
  6784. if use_thread is True:
  6785. with self.proc_container.new(_("Exporting DXF")) as proc:
  6786. def job_thread_exc(app_obj):
  6787. ret_dxf_val = make_dxf()
  6788. if ret_dxf_val == 'fail':
  6789. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6790. return
  6791. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6792. else:
  6793. ret = make_dxf()
  6794. if ret == 'fail':
  6795. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6796. return
  6797. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6798. """
  6799. Adds a new Geometry Object to the projects and populates
  6800. it with shapes extracted from the SVG file.
  6801. :param plot: If True then the resulting object will be plotted on canvas
  6802. :param filename: Path to the SVG file.
  6803. :param geo_type: Type of FlatCAM object that will be created from SVG
  6804. :param outname: The name given to the resulting FlatCAM object
  6805. :return:
  6806. """
  6807. self.defaults.report_usage("import_svg()")
  6808. log.debug("App.import_svg()")
  6809. obj_type = ""
  6810. if geo_type is None or geo_type == "geometry":
  6811. obj_type = "geometry"
  6812. elif geo_type == "gerber":
  6813. obj_type = "gerber"
  6814. else:
  6815. self.inform.emit('[ERROR_NOTCL] %s' %
  6816. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6817. return
  6818. units = self.defaults['units'].upper()
  6819. def obj_init(geo_obj, app_obj):
  6820. geo_obj.import_svg(filename, obj_type, units=units)
  6821. geo_obj.multigeo = False
  6822. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6823. with self.proc_container.new(_("Importing SVG")) as proc:
  6824. # Object name
  6825. name = outname or filename.split('/')[-1].split('\\')[-1]
  6826. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6827. if ret == 'fail':
  6828. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6829. return 'fail'
  6830. # Register recent file
  6831. self.file_opened.emit("svg", filename)
  6832. # AppGUI feedback
  6833. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6834. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6835. """
  6836. Adds a new Geometry Object to the projects and populates
  6837. it with shapes extracted from the DXF file.
  6838. :param filename: Path to the DXF file.
  6839. :param geo_type: Type of FlatCAM object that will be created from DXF
  6840. :param outname: Name for the imported Geometry
  6841. :param plot: If True then the resulting object will be plotted on canvas
  6842. :return:
  6843. """
  6844. self.defaults.report_usage("import_dxf()")
  6845. obj_type = ""
  6846. if geo_type is None or geo_type == "geometry":
  6847. obj_type = "geometry"
  6848. elif geo_type == "gerber":
  6849. obj_type = geo_type
  6850. else:
  6851. self.inform.emit('[ERROR_NOTCL] %s' %
  6852. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6853. return
  6854. units = self.defaults['units'].upper()
  6855. def obj_init(geo_obj, app_obj):
  6856. geo_obj.import_dxf(filename, obj_type, units=units)
  6857. geo_obj.multigeo = False
  6858. with self.proc_container.new(_("Importing DXF")):
  6859. # Object name
  6860. name = outname or filename.split('/')[-1].split('\\')[-1]
  6861. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6862. if ret == 'fail':
  6863. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6864. return 'fail'
  6865. # Register recent file
  6866. self.file_opened.emit("dxf", filename)
  6867. # AppGUI feedback
  6868. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6869. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6870. """
  6871. Opens a Gerber file, parses it and creates a new object for
  6872. it in the program. Thread-safe.
  6873. :param outname: Name of the resulting object. None causes the
  6874. name to be that of the file. Str.
  6875. :param filename: Gerber file filename
  6876. :type filename: str
  6877. :param plot: boolean, to plot or not the resulting object
  6878. :param from_tcl: True if run from Tcl Shell
  6879. :return: None
  6880. """
  6881. # How the object should be initialized
  6882. def obj_init(gerber_obj, app_obj):
  6883. assert isinstance(gerber_obj, GerberObject), \
  6884. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6885. # Opening the file happens here
  6886. try:
  6887. gerber_obj.parse_file(filename)
  6888. except IOError:
  6889. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6890. return "fail"
  6891. except ParseError as err:
  6892. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6893. app_obj.log.error(str(err))
  6894. return "fail"
  6895. except Exception as e:
  6896. log.debug("App.open_gerber() --> %s" % str(e))
  6897. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6898. msg += traceback.format_exc()
  6899. app_obj.inform.emit(msg)
  6900. return "fail"
  6901. if gerber_obj.is_empty():
  6902. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6903. _("Object is not Gerber file or empty. Aborting object creation."))
  6904. return "fail"
  6905. App.log.debug("open_gerber()")
  6906. with self.proc_container.new(_("Opening Gerber")):
  6907. # Object name
  6908. name = outname or filename.split('/')[-1].split('\\')[-1]
  6909. # # ## Object creation # ##
  6910. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6911. if ret_val == 'fail':
  6912. if from_tcl:
  6913. filename = self.defaults['global_tcl_path'] + '/' + name
  6914. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6915. if ret_val == 'fail':
  6916. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6917. return 'fail'
  6918. # Register recent file
  6919. self.file_opened.emit("gerber", filename)
  6920. # AppGUI feedback
  6921. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6922. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6923. """
  6924. Opens an Excellon file, parses it and creates a new object for
  6925. it in the program. Thread-safe.
  6926. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6927. :param filename: Excellon file filename
  6928. :type filename: str
  6929. :param plot: boolean, to plot or not the resulting object
  6930. :param from_tcl: True if run from Tcl Shell
  6931. :return: None
  6932. """
  6933. App.log.debug("open_excellon()")
  6934. # How the object should be initialized
  6935. def obj_init(excellon_obj, app_obj):
  6936. try:
  6937. ret = excellon_obj.parse_file(filename=filename)
  6938. if ret == "fail":
  6939. log.debug("Excellon parsing failed.")
  6940. self.inform.emit('[ERROR_NOTCL] %s' %
  6941. _("This is not Excellon file."))
  6942. return "fail"
  6943. except IOError:
  6944. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6945. (_("Cannot open file"), filename))
  6946. log.debug("Could not open Excellon object.")
  6947. return "fail"
  6948. except Exception:
  6949. msg = '[ERROR_NOTCL] %s' % \
  6950. _("An internal error has occurred. See shell.\n")
  6951. msg += traceback.format_exc()
  6952. app_obj.inform.emit(msg)
  6953. return "fail"
  6954. ret = excellon_obj.create_geometry()
  6955. if ret == 'fail':
  6956. log.debug("Could not create geometry for Excellon object.")
  6957. return "fail"
  6958. for tool in excellon_obj.tools:
  6959. if excellon_obj.tools[tool]['solid_geometry']:
  6960. return
  6961. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6962. return "fail"
  6963. with self.proc_container.new(_("Opening Excellon.")):
  6964. # Object name
  6965. name = outname or filename.split('/')[-1].split('\\')[-1]
  6966. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6967. if ret_val == 'fail':
  6968. if from_tcl:
  6969. filename = self.defaults['global_tcl_path'] + '/' + name
  6970. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6971. if ret_val == 'fail':
  6972. self.inform.emit('[ERROR_NOTCL] %s' %
  6973. _('Open Excellon file failed. Probable not an Excellon file.'))
  6974. return
  6975. # Register recent file
  6976. self.file_opened.emit("excellon", filename)
  6977. # AppGUI feedback
  6978. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6979. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  6980. """
  6981. Opens a G-gcode file, parses it and creates a new object for
  6982. it in the program. Thread-safe.
  6983. :param filename: G-code file filename
  6984. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6985. :param force_parsing:
  6986. :param plot: If True plot the object on canvas
  6987. :param from_tcl: True if run from Tcl Shell
  6988. :return: None
  6989. """
  6990. App.log.debug("open_gcode()")
  6991. # How the object should be initialized
  6992. def obj_init(job_obj, app_obj_):
  6993. """
  6994. :param job_obj: the resulting object
  6995. :type app_obj_: App
  6996. """
  6997. assert isinstance(app_obj_, App), \
  6998. "Initializer expected App, got %s" % type(app_obj_)
  6999. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7000. try:
  7001. f = open(filename)
  7002. gcode = f.read()
  7003. f.close()
  7004. except IOError:
  7005. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7006. return "fail"
  7007. job_obj.gcode = gcode
  7008. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7009. if gcode_ret == "fail":
  7010. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7011. return "fail"
  7012. job_obj.create_geometry()
  7013. with self.proc_container.new(_("Opening G-Code.")):
  7014. # Object name
  7015. name = outname or filename.split('/')[-1].split('\\')[-1]
  7016. # New object creation and file processing
  7017. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7018. if ret_val == 'fail':
  7019. if from_tcl:
  7020. filename = self.defaults['global_tcl_path'] + '/' + name
  7021. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7022. if ret_val == 'fail':
  7023. self.inform.emit('[ERROR_NOTCL] %s' %
  7024. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7025. "Try to load it from File menu.\n "
  7026. "Attempting to create a FlatCAM CNCJob Object from "
  7027. "G-Code file failed during processing"))
  7028. return "fail"
  7029. # Register recent file
  7030. self.file_opened.emit("cncjob", filename)
  7031. # AppGUI feedback
  7032. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7033. def open_hpgl2(self, filename, outname=None):
  7034. """
  7035. Opens a HPGL2 file, parses it and creates a new object for
  7036. it in the program. Thread-safe.
  7037. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7038. :param filename: HPGL2 file filename
  7039. :return: None
  7040. """
  7041. filename = filename
  7042. # How the object should be initialized
  7043. def obj_init(geo_obj, app_obj):
  7044. assert isinstance(geo_obj, GeometryObject), \
  7045. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7046. # Opening the file happens here
  7047. obj = HPGL2(self)
  7048. try:
  7049. HPGL2.parse_file(obj, filename)
  7050. except IOError:
  7051. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7052. return "fail"
  7053. except ParseError as err:
  7054. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7055. app_obj.log.error(str(err))
  7056. return "fail"
  7057. except Exception as e:
  7058. log.debug("App.open_hpgl2() --> %s" % str(e))
  7059. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7060. msg += traceback.format_exc()
  7061. app_obj.inform.emit(msg)
  7062. return "fail"
  7063. geo_obj.multigeo = True
  7064. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7065. geo_obj.tools = deepcopy(obj.tools)
  7066. geo_obj.source_file = deepcopy(obj.source_file)
  7067. del obj
  7068. if not geo_obj.solid_geometry:
  7069. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7070. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7071. return "fail"
  7072. App.log.debug("open_hpgl2()")
  7073. with self.proc_container.new(_("Opening HPGL2")):
  7074. # Object name
  7075. name = outname or filename.split('/')[-1].split('\\')[-1]
  7076. # # ## Object creation # ##
  7077. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7078. if ret == 'fail':
  7079. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7080. return 'fail'
  7081. # Register recent file
  7082. self.file_opened.emit("geometry", filename)
  7083. # AppGUI feedback
  7084. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7085. def open_script(self, filename, outname=None, silent=False):
  7086. """
  7087. Opens a Script file, parses it and creates a new object for
  7088. it in the program. Thread-safe.
  7089. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7090. :param filename: Script file filename
  7091. :param silent: If True there will be no messages printed to StatusBar
  7092. :return: None
  7093. """
  7094. def obj_init(script_obj, app_obj):
  7095. assert isinstance(script_obj, ScriptObject), \
  7096. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7097. if silent is False:
  7098. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7099. try:
  7100. script_obj.parse_file(filename)
  7101. except IOError:
  7102. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7103. return "fail"
  7104. except ParseError as err:
  7105. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7106. app_obj.log.error(str(err))
  7107. return "fail"
  7108. except Exception as e:
  7109. log.debug("App.open_script() -> %s" % str(e))
  7110. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7111. msg += traceback.format_exc()
  7112. app_obj.inform.emit(msg)
  7113. return "fail"
  7114. App.log.debug("open_script()")
  7115. with self.proc_container.new(_("Opening TCL Script...")):
  7116. # Object name
  7117. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7118. # Object creation
  7119. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7120. if ret_val == 'fail':
  7121. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7122. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7123. if ret_val == 'fail':
  7124. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7125. return 'fail'
  7126. # Register recent file
  7127. self.file_opened.emit("script", filename)
  7128. # AppGUI feedback
  7129. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7130. def open_config_file(self, filename, run_from_arg=None):
  7131. """
  7132. Loads a config file from the specified file.
  7133. :param filename: Name of the file from which to load.
  7134. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7135. :return: None
  7136. """
  7137. App.log.debug("Opening config file: " + filename)
  7138. if run_from_arg:
  7139. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7140. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7141. _("Opening FlatCAM Config file.")),
  7142. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7143. color=QtGui.QColor("gray"))
  7144. # # add the tab if it was closed
  7145. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7146. # # first clear previous text in text editor (if any)
  7147. # self.ui.text_editor_tab.code_editor.clear()
  7148. #
  7149. # # Switch plot_area to CNCJob tab
  7150. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7151. # close the Code editor if already open
  7152. if self.toggle_codeeditor:
  7153. self.on_toggle_code_editor()
  7154. self.on_toggle_code_editor()
  7155. try:
  7156. if filename:
  7157. f = QtCore.QFile(filename)
  7158. if f.open(QtCore.QIODevice.ReadOnly):
  7159. stream = QtCore.QTextStream(f)
  7160. code_edited = stream.readAll()
  7161. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7162. f.close()
  7163. except IOError:
  7164. App.log.error("Failed to open config file: %s" % filename)
  7165. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7166. (_("Failed to open config file"), filename))
  7167. return
  7168. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7169. """
  7170. Loads a project from the specified file.
  7171. 1) Loads and parses file
  7172. 2) Registers the file as recently opened.
  7173. 3) Calls on_file_new()
  7174. 4) Updates options
  7175. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7176. 6) Calls plot_all() if plot=True
  7177. :param filename: Name of the file from which to load.
  7178. :param run_from_arg: True if run for arguments
  7179. :param plot: If True plot all objects in the project
  7180. :param cli: Run from command line
  7181. :param from_tcl: True if run from Tcl Sehll
  7182. :return: None
  7183. """
  7184. App.log.debug("Opening project: " + filename)
  7185. # block autosaving while a project is loaded
  7186. self.block_autosave = True
  7187. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7188. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7189. if cli is None:
  7190. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7191. if run_from_arg:
  7192. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7193. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7194. _("Opening FlatCAM Project file.")),
  7195. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7196. color=QtGui.QColor("gray"))
  7197. # Open and parse an uncompressed Project file
  7198. try:
  7199. f = open(filename, 'r')
  7200. except IOError:
  7201. if from_tcl:
  7202. name = filename.split('/')[-1].split('\\')[-1]
  7203. filename = self.defaults['global_tcl_path'] + '/' + name
  7204. try:
  7205. f = open(filename, 'r')
  7206. except IOError:
  7207. log.error("Failed to open project file: %s" % filename)
  7208. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7209. return
  7210. else:
  7211. log.error("Failed to open project file: %s" % filename)
  7212. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7213. return
  7214. try:
  7215. d = json.load(f, object_hook=dict2obj)
  7216. except Exception as e:
  7217. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7218. (filename, str(e)))
  7219. f.close()
  7220. # Open and parse a compressed Project file
  7221. try:
  7222. with lzma.open(filename) as f:
  7223. file_content = f.read().decode('utf-8')
  7224. d = json.loads(file_content, object_hook=dict2obj)
  7225. except Exception as e:
  7226. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7227. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7228. return
  7229. # Clear the current project
  7230. # # NOT THREAD SAFE # ##
  7231. if run_from_arg is True:
  7232. pass
  7233. elif cli is True:
  7234. self.delete_selection_shape()
  7235. else:
  7236. self.on_file_new()
  7237. # Project options
  7238. self.options.update(d['options'])
  7239. self.project_filename = filename
  7240. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7241. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7242. if cli is None:
  7243. self.set_screen_units(self.options["units"])
  7244. # Re create objects
  7245. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7246. for obj in d['objs']:
  7247. try:
  7248. def obj_init(obj_inst, app_inst):
  7249. obj_inst.from_dict(obj)
  7250. App.log.debug("Recreating from opened project an %s object: %s" %
  7251. (obj['kind'].capitalize(), obj['options']['name']))
  7252. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7253. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7254. if cli is None:
  7255. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7256. obj['kind'].upper(),
  7257. obj['options']['name']
  7258. )
  7259. )
  7260. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7261. except Exception as e:
  7262. print('App.open_project() --> ' + str(e))
  7263. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7264. self.should_we_save = False
  7265. self.file_opened.emit("project", filename)
  7266. # restore autosaving after a project was loaded
  7267. self.block_autosave = False
  7268. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7269. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7270. if cli is None:
  7271. self.set_ui_title(name=self.project_filename)
  7272. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7273. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7274. """
  7275. Re-generates all plots from all objects.
  7276. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7277. :param muted: if True don't print messages
  7278. :param use_thread: if True will use threading for plotting the objects
  7279. :return: None
  7280. """
  7281. self.log.debug("Plot_all()")
  7282. if muted is not True:
  7283. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7284. for plot_obj in self.collection.get_list():
  7285. def worker_task(obj):
  7286. with self.proc_container.new("Plotting"):
  7287. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7288. if fit_view is True:
  7289. self.app_obj.object_plotted.emit(obj)
  7290. if use_thread is True:
  7291. # Send to worker
  7292. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7293. else:
  7294. worker_task(plot_obj)
  7295. def register_folder(self, filename):
  7296. """
  7297. Register the last folder used by the app to open something
  7298. :param filename: the last folder is extracted from the filename
  7299. :return: None
  7300. """
  7301. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7302. def register_save_folder(self, filename):
  7303. """
  7304. Register the last folder used by the app to save something
  7305. :param filename: the last folder is extracted from the filename
  7306. :return: None
  7307. """
  7308. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7309. # def set_progress_bar(self, percentage, text=""):
  7310. # """
  7311. # Set a progress bar to a value (percentage)
  7312. #
  7313. # :param percentage: Value set to the progressbar
  7314. # :param text: Not used
  7315. # :return: None
  7316. # """
  7317. # self.ui.progress_bar.setValue(int(percentage))
  7318. def setup_recent_items(self):
  7319. """
  7320. Setup a dictionary with the recent files accessed, organized by type
  7321. :return:
  7322. """
  7323. icons = {
  7324. "gerber": self.resource_location + "/flatcam_icon16.png",
  7325. "excellon": self.resource_location + "/drill16.png",
  7326. 'geometry': self.resource_location + "/geometry16.png",
  7327. "cncjob": self.resource_location + "/cnc16.png",
  7328. "script": self.resource_location + "/script_new24.png",
  7329. "document": self.resource_location + "/notes16_1.png",
  7330. "project": self.resource_location + "/project16.png",
  7331. "svg": self.resource_location + "/geometry16.png",
  7332. "dxf": self.resource_location + "/dxf16.png",
  7333. "pdf": self.resource_location + "/pdf32.png",
  7334. "image": self.resource_location + "/image16.png"
  7335. }
  7336. try:
  7337. image_opener = self.image_tool.import_image
  7338. except AttributeError:
  7339. image_opener = None
  7340. openers = {
  7341. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7342. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7343. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7344. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7345. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7346. "document": None,
  7347. 'project': self.open_project,
  7348. 'svg': self.import_svg,
  7349. 'dxf': self.import_dxf,
  7350. 'image': image_opener,
  7351. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7352. }
  7353. # Open recent file for files
  7354. try:
  7355. f = open(self.data_path + '/recent.json')
  7356. except IOError:
  7357. App.log.error("Failed to load recent item list.")
  7358. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7359. return
  7360. try:
  7361. self.recent = json.load(f)
  7362. except json.errors.JSONDecodeError:
  7363. App.log.error("Failed to parse recent item list.")
  7364. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7365. f.close()
  7366. return
  7367. f.close()
  7368. # Open recent file for projects
  7369. try:
  7370. fp = open(self.data_path + '/recent_projects.json')
  7371. except IOError:
  7372. App.log.error("Failed to load recent project item list.")
  7373. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7374. return
  7375. try:
  7376. self.recent_projects = json.load(fp)
  7377. except json.errors.JSONDecodeError:
  7378. App.log.error("Failed to parse recent project item list.")
  7379. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7380. fp.close()
  7381. return
  7382. fp.close()
  7383. # Closure needed to create callbacks in a loop.
  7384. # Otherwise late binding occurs.
  7385. def make_callback(func, fname):
  7386. def opener():
  7387. func(fname)
  7388. return opener
  7389. def reset_recent_files():
  7390. # Reset menu
  7391. self.ui.recent.clear()
  7392. self.recent = []
  7393. try:
  7394. ff = open(self.data_path + '/recent.json', 'w')
  7395. except IOError:
  7396. App.log.error("Failed to open recent items file for writing.")
  7397. return
  7398. json.dump(self.recent, ff)
  7399. def reset_recent_projects():
  7400. # Reset menu
  7401. self.ui.recent_projects.clear()
  7402. self.recent_projects = []
  7403. try:
  7404. frp = open(self.data_path + '/recent_projects.json', 'w')
  7405. except IOError:
  7406. App.log.error("Failed to open recent projects items file for writing.")
  7407. return
  7408. json.dump(self.recent, frp)
  7409. # Reset menu
  7410. self.ui.recent.clear()
  7411. self.ui.recent_projects.clear()
  7412. # Create menu items for projects
  7413. for recent in self.recent_projects:
  7414. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7415. if recent['kind'] == 'project':
  7416. try:
  7417. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7418. # Attach callback
  7419. o = make_callback(openers[recent["kind"]], recent['filename'])
  7420. action.triggered.connect(o)
  7421. self.ui.recent_projects.addAction(action)
  7422. except KeyError:
  7423. App.log.error("Unsupported file type: %s" % recent["kind"])
  7424. # Last action in Recent Files menu is one that Clear the content
  7425. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7426. (_("Clear Recent projects")), self)
  7427. clear_action_proj.triggered.connect(reset_recent_projects)
  7428. self.ui.recent_projects.addSeparator()
  7429. self.ui.recent_projects.addAction(clear_action_proj)
  7430. # Create menu items for files
  7431. for recent in self.recent:
  7432. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7433. if recent['kind'] != 'project':
  7434. try:
  7435. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7436. # Attach callback
  7437. o = make_callback(openers[recent["kind"]], recent['filename'])
  7438. action.triggered.connect(o)
  7439. self.ui.recent.addAction(action)
  7440. except KeyError:
  7441. App.log.error("Unsupported file type: %s" % recent["kind"])
  7442. # Last action in Recent Files menu is one that Clear the content
  7443. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7444. (_("Clear Recent files")), self)
  7445. clear_action.triggered.connect(reset_recent_files)
  7446. self.ui.recent.addSeparator()
  7447. self.ui.recent.addAction(clear_action)
  7448. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7449. # self.ui.menufilerecent.set_submenu(recent_menu)
  7450. # recent_menu.show_all()
  7451. # self.ui.recent.show()
  7452. self.log.debug("Recent items list has been populated.")
  7453. def setup_component_editor(self):
  7454. """
  7455. Default text for the Selected tab when is not taken by the Object UI.
  7456. :return:
  7457. """
  7458. # label = QtWidgets.QLabel("Choose an item from Project")
  7459. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7460. sel_title = QtWidgets.QTextEdit(
  7461. _('<b>Shortcut Key List</b>'))
  7462. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7463. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7464. f_settings = QSettings("Open Source", "FlatCAM")
  7465. if f_settings.contains("notebook_font_size"):
  7466. fsize = f_settings.value('notebook_font_size', type=int)
  7467. else:
  7468. fsize = 12
  7469. tsize = fsize + int(fsize / 2)
  7470. # selected_text = (_('''
  7471. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7472. # </p>
  7473. #
  7474. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7475. # The normal flow when working in FlatCAM is the following:</span></p>
  7476. #
  7477. # <ol>
  7478. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7479. # file into
  7480. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7481. # even dragging and dropping the files on the AppGUI.<br />
  7482. # <br />
  7483. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7484. # drop of the
  7485. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7486. # &nbsp;</li>
  7487. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7488. # and then
  7489. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7490. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7491. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7492. # <br />
  7493. # If the selection of the object is done on the canvas by single click instead, and the
  7494. # <strong>SELECTED TAB</strong>
  7495. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7496. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7497. # it even if it was out of focus.<br />
  7498. # <br />
  7499. # You can change the parameters in this screen and the flow direction is like this:<br />
  7500. # <br />
  7501. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7502. # <strong> Geometry Object
  7503. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7504. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7505. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7506. # </ol>
  7507. #
  7508. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7509. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7510. # <strong>F3</strong>.</span></p>
  7511. #
  7512. # ''').format(fsize=fsize, tsize=tsize))
  7513. selected_text = '''
  7514. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7515. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7516. {s1}</span></p>
  7517. <ol>
  7518. <li><span style="font-size:{fsize}px">{s2}<br />
  7519. <br />
  7520. {s3}</span><br />
  7521. &nbsp;</li>
  7522. <li><span style="font-size:{fsize}px">{s4}<br />
  7523. &nbsp;</li>
  7524. <br />
  7525. <li><span style="font-size:{fsize}px">{s5}<br />
  7526. &nbsp;</li>
  7527. <br />
  7528. <li><span style="font-size:{fsize}px">{s6}<br />
  7529. <br />
  7530. {s7}</span></li>
  7531. </ol>
  7532. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7533. '''.format(
  7534. title=_("Selected Tab - Choose an Item from Project Tab"),
  7535. subtitle=_("Details"),
  7536. s1=_("The normal flow when working in FlatCAM is the following:"),
  7537. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7538. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7539. "files on the AppGUI."),
  7540. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7541. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7542. "actions offered within the app."),
  7543. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7544. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7545. "SELECTED TAB will be updated with the object properties according to its kind: "
  7546. "Gerber, Excellon, Geometry or CNCJob object."),
  7547. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7548. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7549. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7550. "the SELECTED TAB and populate it even if it was out of focus."),
  7551. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7552. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7553. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7554. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7555. "(again, done in SELECTED TAB) --> Save GCode."),
  7556. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7557. "or through its own key shortcut: <b>F3</b>."),
  7558. tsize=tsize,
  7559. fsize=fsize
  7560. )
  7561. sel_title.setText(selected_text)
  7562. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7563. self.ui.selected_scroll_area.setWidget(sel_title)
  7564. def setup_obj_classes(self):
  7565. """
  7566. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7567. class.
  7568. :return: None
  7569. """
  7570. FlatCAMObj.app = self
  7571. ObjectCollection.app = self
  7572. Gerber.app = self
  7573. Excellon.app = self
  7574. Geometry.app = self
  7575. CNCjob.app = self
  7576. FCProcess.app = self
  7577. FCProcessContainer.app = self
  7578. OptionsGroupUI.app = self
  7579. def version_check(self):
  7580. """
  7581. Checks for the latest version of the program. Alerts the
  7582. user if theirs is outdated. This method is meant to be run
  7583. in a separate thread.
  7584. :return: None
  7585. """
  7586. self.log.debug("version_check()")
  7587. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7588. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7589. App.version_url,
  7590. str(self.defaults['global_serial']),
  7591. str(self.version),
  7592. str(self.os),
  7593. urllib.parse.urlencode(self.defaults["global_stats"])
  7594. )
  7595. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7596. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7597. # urllib.parse.urlencode(self.defaults["global_stats"])
  7598. else:
  7599. # no_stats dict; just so it won't break things on website
  7600. no_ststs_dict = {}
  7601. no_ststs_dict["global_ststs"] = {}
  7602. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7603. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7604. App.log.debug("Checking for updates @ %s" % full_url)
  7605. # ## Get the data
  7606. try:
  7607. f = urllib.request.urlopen(full_url)
  7608. except Exception:
  7609. # App.log.warning("Failed checking for latest version. Could not connect.")
  7610. self.log.warning("Failed checking for latest version. Could not connect.")
  7611. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7612. return
  7613. try:
  7614. data = json.load(f)
  7615. except Exception as e:
  7616. App.log.error("Could not parse information about latest version.")
  7617. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7618. App.log.debug("json.load(): %s" % str(e))
  7619. f.close()
  7620. return
  7621. f.close()
  7622. # ## Latest version?
  7623. if self.version >= data["version"]:
  7624. App.log.debug("FlatCAM is up to date!")
  7625. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7626. return
  7627. App.log.debug("Newer version available.")
  7628. self.message.emit(
  7629. _("Newer Version Available"),
  7630. '%s<br><br>><b>%s</b><br>%s' % (
  7631. _("There is a newer version of FlatCAM available for download:"),
  7632. str(data["name"]),
  7633. str(data["message"])
  7634. ),
  7635. _("info")
  7636. )
  7637. def on_plotcanvas_setup(self, container=None):
  7638. """
  7639. This is doing the setup for the plot area (canvas).
  7640. :param container: QT Widget where to install the canvas
  7641. :return: None
  7642. """
  7643. if container:
  7644. plot_container = container
  7645. else:
  7646. plot_container = self.ui.right_layout
  7647. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7648. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7649. self.is_legacy = True
  7650. self.defaults["global_graphic_engine"] = "2D"
  7651. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7652. else:
  7653. try:
  7654. self.plotcanvas = PlotCanvas(plot_container, self)
  7655. except Exception as er:
  7656. msg_txt = traceback.format_exc()
  7657. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7658. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7659. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7660. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7661. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7662. msg += msg_txt
  7663. self.inform.emit(msg)
  7664. return 'fail'
  7665. # So it can receive key presses
  7666. self.plotcanvas.native.setFocus()
  7667. if self.is_legacy is False:
  7668. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7669. # Set the mouse button for panning
  7670. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7671. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7672. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7673. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7674. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7675. # Keys over plot enabled
  7676. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7677. if self.defaults['global_cursor_type'] == 'small':
  7678. self.app_cursor = self.plotcanvas.new_cursor()
  7679. else:
  7680. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7681. if self.ui.grid_snap_btn.isChecked():
  7682. self.app_cursor.enabled = True
  7683. else:
  7684. self.app_cursor.enabled = False
  7685. if self.is_legacy is False:
  7686. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7687. else:
  7688. # will use the default Matplotlib axes
  7689. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7690. def on_zoom_fit(self):
  7691. """
  7692. Callback for zoom-fit request. This can be either from the corresponding
  7693. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7694. with axes limits from the geometry bounds of all objects.
  7695. :return: None
  7696. """
  7697. if self.is_legacy is False:
  7698. self.plotcanvas.fit_view()
  7699. else:
  7700. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7701. width = xmax - xmin
  7702. height = ymax - ymin
  7703. xmin -= 0.05 * width
  7704. xmax += 0.05 * width
  7705. ymin -= 0.05 * height
  7706. ymax += 0.05 * height
  7707. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7708. def on_zoom_in(self):
  7709. """
  7710. Callback for zoom-in request.
  7711. :return:
  7712. """
  7713. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7714. def on_zoom_out(self):
  7715. """
  7716. Callback for zoom-out request.
  7717. :return:
  7718. """
  7719. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7720. def disable_all_plots(self):
  7721. self.defaults.report_usage("disable_all_plots()")
  7722. self.disable_plots(self.collection.get_list())
  7723. self.inform.emit('[success] %s' %
  7724. _("All plots disabled."))
  7725. def disable_other_plots(self):
  7726. self.defaults.report_usage("disable_other_plots()")
  7727. self.disable_plots(self.collection.get_non_selected())
  7728. self.inform.emit('[success] %s' %
  7729. _("All non selected plots disabled."))
  7730. def enable_all_plots(self):
  7731. self.defaults.report_usage("enable_all_plots()")
  7732. self.enable_plots(self.collection.get_list())
  7733. self.inform.emit('[success] %s' %
  7734. _("All plots enabled."))
  7735. def on_enable_sel_plots(self):
  7736. log.debug("App.on_enable_sel_plot()")
  7737. object_list = self.collection.get_selected()
  7738. self.enable_plots(objects=object_list)
  7739. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7740. def on_disable_sel_plots(self):
  7741. log.debug("App.on_disable_sel_plot()")
  7742. # self.inform.emit(_("Disabling plots ..."))
  7743. object_list = self.collection.get_selected()
  7744. self.disable_plots(objects=object_list)
  7745. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7746. def enable_plots(self, objects):
  7747. """
  7748. Enable plots
  7749. :param objects: list of Objects to be enabled
  7750. :return:
  7751. """
  7752. log.debug("Enabling plots ...")
  7753. # self.inform.emit(_("Working ..."))
  7754. for obj in objects:
  7755. if obj.options['plot'] is False:
  7756. obj.options.set_change_callback(lambda x: None)
  7757. obj.options['plot'] = True
  7758. try:
  7759. # only the Gerber obj has on_plot_cb_click() method
  7760. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7761. # disable this cb while disconnected,
  7762. # in case the operation takes time the user is not allowed to change it
  7763. obj.ui.plot_cb.setDisabled(True)
  7764. except AttributeError:
  7765. pass
  7766. obj.set_form_item("plot")
  7767. try:
  7768. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7769. obj.ui.plot_cb.setDisabled(False)
  7770. except AttributeError:
  7771. pass
  7772. obj.options.set_change_callback(obj.on_options_change)
  7773. def worker_task(objs):
  7774. with self.proc_container.new(_("Enabling plots ...")):
  7775. for plot_obj in objs:
  7776. # obj.options['plot'] = True
  7777. if isinstance(plot_obj, CNCJobObject):
  7778. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7779. else:
  7780. plot_obj.plot(visible=True)
  7781. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7782. def disable_plots(self, objects):
  7783. """
  7784. Disables plots
  7785. :param objects: list of Objects to be disabled
  7786. :return:
  7787. """
  7788. # if no objects selected then do nothing
  7789. if not self.collection.get_selected():
  7790. return
  7791. log.debug("Disabling plots ...")
  7792. # self.inform.emit(_("Working ..."))
  7793. for obj in objects:
  7794. if obj.options['plot'] is True:
  7795. obj.options.set_change_callback(lambda x: None)
  7796. obj.options['plot'] = False
  7797. try:
  7798. # only the Gerber obj has on_plot_cb_click() method
  7799. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7800. obj.ui.plot_cb.setDisabled(True)
  7801. except AttributeError:
  7802. pass
  7803. obj.set_form_item("plot")
  7804. try:
  7805. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7806. obj.ui.plot_cb.setDisabled(False)
  7807. except AttributeError:
  7808. pass
  7809. obj.options.set_change_callback(obj.on_options_change)
  7810. try:
  7811. self.delete_selection_shape()
  7812. except Exception as e:
  7813. log.debug("App.disable_plots() --> %s" % str(e))
  7814. def worker_task(objs):
  7815. with self.proc_container.new(_("Disabling plots ...")):
  7816. for plot_obj in objs:
  7817. # obj.options['plot'] = True
  7818. if isinstance(plot_obj, CNCJobObject):
  7819. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7820. else:
  7821. plot_obj.plot(visible=False)
  7822. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7823. def toggle_plots(self, objects):
  7824. """
  7825. Toggle plots visibility
  7826. :param objects: list of Objects for which to be toggled the visibility
  7827. :return: None
  7828. """
  7829. # if no objects selected then do nothing
  7830. if not self.collection.get_selected():
  7831. return
  7832. log.debug("Toggling plots ...")
  7833. self.inform.emit(_("Working ..."))
  7834. for obj in objects:
  7835. if obj.options['plot'] is False:
  7836. obj.options['plot'] = True
  7837. else:
  7838. obj.options['plot'] = False
  7839. self.app_obj.plots_updated.emit()
  7840. def clear_plots(self):
  7841. """
  7842. Clear the plots
  7843. :return: None
  7844. """
  7845. objects = self.collection.get_list()
  7846. for obj in objects:
  7847. obj.clear(obj == objects[-1])
  7848. # Clear pool to free memory
  7849. self.clear_pool()
  7850. def on_set_color_action_triggered(self):
  7851. """
  7852. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7853. :return:
  7854. """
  7855. new_color = self.defaults['gerber_plot_fill']
  7856. clicked_action = self.sender()
  7857. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7858. act_name = clicked_action.text()
  7859. sel_obj_list = self.collection.get_selected()
  7860. if not sel_obj_list:
  7861. return
  7862. # a default value, I just chose this one
  7863. alpha_level = 'BF'
  7864. for sel_obj in sel_obj_list:
  7865. if sel_obj.kind == 'excellon':
  7866. alpha_level = str(hex(
  7867. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7868. elif sel_obj.kind == 'gerber':
  7869. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7870. elif sel_obj.kind == 'geometry':
  7871. alpha_level = 'FF'
  7872. else:
  7873. log.debug(
  7874. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7875. continue
  7876. sel_obj.alpha_level = alpha_level
  7877. if act_name == _('Red'):
  7878. new_color = '#FF0000' + alpha_level
  7879. if act_name == _('Blue'):
  7880. new_color = '#0000FF' + alpha_level
  7881. if act_name == _('Yellow'):
  7882. new_color = '#FFDF00' + alpha_level
  7883. if act_name == _('Green'):
  7884. new_color = '#00FF00' + alpha_level
  7885. if act_name == _('Purple'):
  7886. new_color = '#FF00FF' + alpha_level
  7887. if act_name == _('Brown'):
  7888. new_color = '#A52A2A' + alpha_level
  7889. if act_name == _('White'):
  7890. new_color = '#FFFFFF' + alpha_level
  7891. if act_name == _('Black'):
  7892. new_color = '#000000' + alpha_level
  7893. if act_name == _('Custom'):
  7894. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7895. c_dialog = QtWidgets.QColorDialog()
  7896. plot_fill_color = c_dialog.getColor(initial=new_color)
  7897. if plot_fill_color.isValid() is False:
  7898. return
  7899. new_color = str(plot_fill_color.name()) + alpha_level
  7900. if act_name == _("Default"):
  7901. for sel_obj in sel_obj_list:
  7902. if sel_obj.kind == 'excellon':
  7903. new_color = self.defaults['excellon_plot_fill']
  7904. new_line_color = self.defaults['excellon_plot_line']
  7905. elif sel_obj.kind == 'gerber':
  7906. new_color = self.defaults['gerber_plot_fill']
  7907. new_line_color = self.defaults['gerber_plot_line']
  7908. elif sel_obj.kind == 'geometry':
  7909. new_color = self.defaults['geometry_plot_line']
  7910. new_line_color = self.defaults['geometry_plot_line']
  7911. else:
  7912. log.debug(
  7913. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7914. continue
  7915. sel_obj.fill_color = new_color
  7916. sel_obj.outline_color = new_line_color
  7917. sel_obj.shapes.redraw(
  7918. update_colors=(new_color, new_line_color)
  7919. )
  7920. return
  7921. if act_name == _("Opacity"):
  7922. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7923. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7924. if ok_button:
  7925. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7926. for sel_obj in sel_obj_list:
  7927. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7928. sel_obj.shapes.redraw(
  7929. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7930. )
  7931. return
  7932. new_line_color = color_variant(new_color[:7], 0.7)
  7933. if act_name == _("White"):
  7934. new_line_color = color_variant("#dedede", 0.7)
  7935. for sel_obj in sel_obj_list:
  7936. sel_obj.fill_color = new_color
  7937. sel_obj.outline_color = new_line_color
  7938. sel_obj.shapes.redraw(
  7939. update_colors=(new_color, new_line_color)
  7940. )
  7941. def generate_cnc_job(self, objects):
  7942. """
  7943. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7944. :param objects: Selected objects in the Project Tab
  7945. :return:
  7946. """
  7947. self.defaults.report_usage("generate_cnc_job()")
  7948. # for obj in objects:
  7949. # obj.generatecncjob()
  7950. for obj in objects:
  7951. obj.on_generatecnc_button_click()
  7952. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7953. """
  7954. Saves the current project to the specified file.
  7955. :param filename: Name of the file in which to save.
  7956. :type filename: str
  7957. :param quit_action: if the project saving will be followed by an app quit; boolean
  7958. :param silent: if True will not display status messages
  7959. :param from_tcl True is run from Tcl Shell
  7960. :return: None
  7961. """
  7962. self.log.debug("save_project()")
  7963. self.save_in_progress = True
  7964. with self.proc_container.new(_("Saving FlatCAM Project")):
  7965. # Capture the latest changes
  7966. # Current object
  7967. try:
  7968. current_object = self.collection.get_active()
  7969. if current_object:
  7970. current_object.read_form()
  7971. except Exception as e:
  7972. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  7973. pass
  7974. # Serialize the whole project
  7975. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7976. "options": self.options,
  7977. "version": self.version}
  7978. if self.defaults["global_save_compressed"] is True:
  7979. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7980. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7981. # # Write
  7982. f.write(g)
  7983. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7984. else:
  7985. # Open file
  7986. try:
  7987. f = open(filename, 'w')
  7988. except IOError:
  7989. App.log.error("Failed to open file for saving: %s", filename)
  7990. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  7991. return
  7992. # Write
  7993. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7994. f.close()
  7995. # verification of the saved project
  7996. # Open and parse
  7997. try:
  7998. saved_f = open(filename, 'r')
  7999. except IOError:
  8000. if silent is False:
  8001. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8002. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8003. return
  8004. try:
  8005. saved_d = json.load(saved_f, object_hook=dict2obj)
  8006. except Exception:
  8007. if silent is False:
  8008. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8009. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8010. f.close()
  8011. return
  8012. saved_f.close()
  8013. if silent is False:
  8014. if 'version' in saved_d:
  8015. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8016. else:
  8017. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8018. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8019. tb_settings = QSettings("Open Source", "FlatCAM")
  8020. lock_state = self.ui.lock_action.isChecked()
  8021. tb_settings.setValue('toolbar_lock', lock_state)
  8022. # This will write the setting to the platform specific storage.
  8023. del tb_settings
  8024. # if quit:
  8025. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8026. # t.start()
  8027. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8028. def start_delayed_quit(self, delay, filename, should_quit=None):
  8029. """
  8030. :param delay: period of checking if project file size is more than zero; in seconds
  8031. :param filename: the name of the project file to be checked periodically for size more than zero
  8032. :param should_quit: if the task finished will be followed by an app quit; boolean
  8033. :return:
  8034. """
  8035. to_quit = should_quit
  8036. self.save_timer = QtCore.QTimer()
  8037. self.save_timer.setInterval(delay)
  8038. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8039. self.save_timer.start()
  8040. def check_project_file_size(self, filename, should_quit=None):
  8041. """
  8042. :param filename: the name of the project file to be checked periodically for size more than zero
  8043. :param should_quit: will quit the app if True; boolean
  8044. :return:
  8045. """
  8046. try:
  8047. if os.stat(filename).st_size > 0:
  8048. self.save_in_progress = False
  8049. self.save_timer.stop()
  8050. if should_quit:
  8051. self.app_quit.emit()
  8052. except Exception:
  8053. traceback.print_exc()
  8054. def save_project_auto(self):
  8055. """
  8056. Called periodically to save the project.
  8057. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8058. # progress.
  8059. :return:
  8060. """
  8061. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8062. self.on_file_saveproject()
  8063. def save_project_auto_update(self):
  8064. """
  8065. Update the auto save time interval value.
  8066. :return:
  8067. """
  8068. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8069. try:
  8070. if self.autosave_timer.isActive():
  8071. self.autosave_timer.stop()
  8072. except Exception:
  8073. pass
  8074. if self.defaults['global_autosave'] is True:
  8075. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8076. self.autosave_timer.start()
  8077. def on_options_app2project(self):
  8078. """
  8079. Callback for Options->Transfer Options->App=>Project. Copies options
  8080. from application defaults to project defaults.
  8081. :return: None
  8082. """
  8083. self.defaults.report_usage("on_options_app2project")
  8084. self.preferencesUiManager.defaults_read_form()
  8085. self.options.update(self.defaults)
  8086. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8087. """
  8088. Shows a message on the FlatCAM Shell
  8089. :param msg: Message to display.
  8090. :param show: Opens the shell.
  8091. :param error: Shows the message as an error.
  8092. :param warning: Shows the message as an warning.
  8093. :param success: Shows the message as an success.
  8094. :param selected: Indicate that something was selected on canvas
  8095. :return: None
  8096. """
  8097. if show:
  8098. self.ui.shell_dock.show()
  8099. try:
  8100. if error:
  8101. self.shell.append_error(msg + "\n")
  8102. elif warning:
  8103. self.shell.append_warning(msg + "\n")
  8104. elif success:
  8105. self.shell.append_success(msg + "\n")
  8106. elif selected:
  8107. self.shell.append_selected(msg + "\n")
  8108. else:
  8109. self.shell.append_output(msg + "\n")
  8110. except AttributeError:
  8111. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8112. class ArgsThread(QtCore.QObject):
  8113. open_signal = pyqtSignal(list)
  8114. start = pyqtSignal()
  8115. stop = pyqtSignal()
  8116. if sys.platform == 'win32':
  8117. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8118. else:
  8119. address = ('/tmp/testipc', 'AF_UNIX')
  8120. def __init__(self):
  8121. super(ArgsThread, self).__init__()
  8122. self.listener = None
  8123. self.thread_exit = False
  8124. self.start.connect(self.run)
  8125. self.stop.connect(self.close_listener)
  8126. def my_loop(self, address):
  8127. try:
  8128. self.listener = Listener(*address)
  8129. while self.thread_exit is False:
  8130. conn = self.listener.accept()
  8131. self.serve(conn)
  8132. except socket.error:
  8133. try:
  8134. conn = Client(*address)
  8135. conn.send(sys.argv)
  8136. conn.send('close')
  8137. # close the current instance only if there are args
  8138. if len(sys.argv) > 1:
  8139. try:
  8140. self.listener.close()
  8141. except Exception:
  8142. pass
  8143. sys.exit()
  8144. except ConnectionRefusedError:
  8145. if sys.platform == 'win32':
  8146. pass
  8147. else:
  8148. os.system('rm /tmp/testipc')
  8149. self.listener = Listener(*address)
  8150. while True:
  8151. conn = self.listener.accept()
  8152. self.serve(conn)
  8153. def serve(self, conn):
  8154. while self.thread_exit is False:
  8155. msg = conn.recv()
  8156. if msg == 'close':
  8157. break
  8158. self.open_signal.emit(msg)
  8159. conn.close()
  8160. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8161. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8162. @pyqtSlot()
  8163. def run(self):
  8164. self.my_loop(self.address)
  8165. @pyqtSlot()
  8166. def close_listener(self):
  8167. self.thread_exit = True
  8168. self.listener.close()
  8169. # end of file