app_Main.py 469 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442
  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 shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from Common import LoudDict
  39. from Common import color_variant
  40. from Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appParsers.ParseHPGL2 import HPGL2
  70. # FlatCAM Workers
  71. from appProcess import *
  72. from appWorkerStack import WorkerStack
  73. # FlatCAM Tools
  74. from appTools import *
  75. # FlatCAM Translation
  76. import gettext
  77. import appTranslation as fcTranslate
  78. import builtins
  79. if sys.platform == 'win32':
  80. import winreg
  81. from win32comext.shell import shell, shellcon
  82. fcTranslate.apply_language('strings')
  83. if '_' not in builtins.__dict__:
  84. _ = gettext.gettext
  85. class App(QtCore.QObject):
  86. """
  87. The main application class. The constructor starts the GUI and all other classes used by the program.
  88. """
  89. # ###############################################################################################################
  90. # ########################################## App ################################################################
  91. # ###############################################################################################################
  92. # ###############################################################################################################
  93. # ######################################### LOGGING #############################################################
  94. # ###############################################################################################################
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ###############################################################################################################
  103. # #################################### Get Cmd Line Options #####################################################
  104. # ###############################################################################################################
  105. cmd_line_shellfile = ''
  106. cmd_line_shellvar = ''
  107. cmd_line_headless = None
  108. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  109. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  110. "FlatCam.py --headless=1"
  111. try:
  112. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  113. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  114. "shellvar=",
  115. "headless=",
  116. "multiprocessing-fork="])
  117. except getopt.GetoptError:
  118. print(cmd_line_help)
  119. sys.exit(2)
  120. for opt, arg in cmd_line_options:
  121. if opt == '-h':
  122. print(cmd_line_help)
  123. sys.exit()
  124. elif opt == '--shellfile':
  125. cmd_line_shellfile = arg
  126. elif opt == '--shellvar':
  127. cmd_line_shellvar = arg
  128. elif opt == '--headless':
  129. try:
  130. cmd_line_headless = eval(arg)
  131. except NameError:
  132. pass
  133. # ###############################################################################################################
  134. # ################################### Version and VERSION DATE ##################################################
  135. # ###############################################################################################################
  136. version = "Unstable Version"
  137. # version = 8.994
  138. version_date = "2020/07/05"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by: App.info() --> Print on the status bar
  169. inform = QtCore.pyqtSignal([str], [str, bool])
  170. # Handled by: App.info_shell() --> Print on the shell
  171. inform_shell = QtCore.pyqtSignal(str)
  172. app_quit = QtCore.pyqtSignal()
  173. # General purpose background task
  174. worker_task = QtCore.pyqtSignal(dict)
  175. # File opened
  176. # Handled by:
  177. # * register_folder()
  178. # * register_recent()
  179. # Note: Setting the parameters to unicode does not seem
  180. # to have an effect. Then are received as Qstring
  181. # anyway.
  182. # File type and filename
  183. file_opened = QtCore.pyqtSignal(str, str)
  184. # File type and filename
  185. file_saved = QtCore.pyqtSignal(str, str)
  186. # Percentage of progress
  187. progress = QtCore.pyqtSignal(int)
  188. # Emitted when a new object has been added or deleted from/to the collection
  189. object_status_changed = QtCore.pyqtSignal(object, str, str)
  190. message = QtCore.pyqtSignal(str, str, str)
  191. # Emmited when shell command is finished(one command only)
  192. shell_command_finished = QtCore.pyqtSignal(object)
  193. # Emitted when multiprocess pool has been recreated
  194. pool_recreated = QtCore.pyqtSignal(object)
  195. # Emitted when an unhandled exception happens
  196. # in the worker task.
  197. thread_exception = QtCore.pyqtSignal(object)
  198. # used to signal that there are arguments for the app
  199. args_at_startup = QtCore.pyqtSignal(list)
  200. # a reusable signal to replot a list of objects
  201. # should be disconnected after use so it can be reused
  202. replot_signal = pyqtSignal(list)
  203. # signal emitted when jumping
  204. jump_signal = pyqtSignal(tuple)
  205. # signal emitted when jumping
  206. locate_signal = pyqtSignal(tuple, str)
  207. # close app signal
  208. close_app_signal = pyqtSignal()
  209. # will perform the cleanup operation after a Graceful Exit
  210. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  211. # graphic residues behind
  212. cleanup = pyqtSignal()
  213. def __init__(self, user_defaults=True):
  214. """
  215. Starts the application.
  216. :return: app
  217. :rtype: App
  218. """
  219. super().__init__()
  220. App.log.info("FlatCAM Starting...")
  221. # ############################################################################################################
  222. # ################# Setup the listening thread for another instance launching with args ######################
  223. # ############################################################################################################
  224. if sys.platform == 'win32' or sys.platform == 'linux':
  225. # make sure the thread is stored by using a self. otherwise it's garbage collected
  226. self.listen_th = QtCore.QThread()
  227. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  228. self.new_launch = ArgsThread()
  229. self.new_launch.open_signal[list].connect(self.on_startup_args)
  230. self.new_launch.moveToThread(self.listen_th)
  231. self.new_launch.start.emit()
  232. # ############################################################################################################
  233. # ########################################## OS-specific #####################################################
  234. # ############################################################################################################
  235. portable = False
  236. # Folder for user settings.
  237. if sys.platform == 'win32':
  238. if platform.architecture()[0] == '32bit':
  239. App.log.debug("Win32!")
  240. else:
  241. App.log.debug("Win64!")
  242. # #######################################################################################################
  243. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  244. # #######################################################################################################
  245. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  246. try:
  247. with open(config_file, 'r'):
  248. pass
  249. except FileNotFoundError:
  250. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  251. try:
  252. with open(config_file, 'r') as f:
  253. try:
  254. for line in f:
  255. param = str(line).replace('\n', '').rpartition('=')
  256. if param[0] == 'portable':
  257. try:
  258. portable = eval(param[2])
  259. except NameError:
  260. portable = False
  261. if param[0] == 'headless':
  262. if param[2].lower() == 'true':
  263. self.cmd_line_headless = 1
  264. else:
  265. self.cmd_line_headless = None
  266. except Exception as e:
  267. log.debug('App.__init__() -->%s' % str(e))
  268. return
  269. except FileNotFoundError as e:
  270. log.debug(str(e))
  271. pass
  272. if portable is False:
  273. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  274. else:
  275. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  276. self.os = 'windows'
  277. else: # Linux/Unix/MacOS
  278. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  279. self.os = 'unix'
  280. # ############################################################################################################
  281. # ################################# Setup folders and files ##################################################
  282. # ############################################################################################################
  283. if not os.path.exists(self.data_path):
  284. os.makedirs(self.data_path)
  285. App.log.debug('Created data folder: ' + self.data_path)
  286. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  287. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  288. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  289. if not os.path.exists(self.preprocessorpaths):
  290. os.makedirs(self.preprocessorpaths)
  291. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  292. # create tools_db.FlatDB file if there is none
  293. try:
  294. f = open(self.data_path + '/tools_db.FlatDB')
  295. f.close()
  296. except IOError:
  297. App.log.debug('Creating empty tools_db.FlatDB')
  298. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  299. json.dump({}, f)
  300. f.close()
  301. # create current_defaults.FlatConfig file if there is none
  302. try:
  303. f = open(self.data_path + '/current_defaults.FlatConfig')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty current_defaults.FlatConfig')
  307. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # the factory defaults are written only once at the first launch of the application after installation
  311. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  312. # create a recent files json file if there is none
  313. try:
  314. f = open(self.data_path + '/recent.json')
  315. f.close()
  316. except IOError:
  317. App.log.debug('Creating empty recent.json')
  318. f = open(self.data_path + '/recent.json', 'w')
  319. json.dump([], f)
  320. f.close()
  321. # create a recent projects json file if there is none
  322. try:
  323. fp = open(self.data_path + '/recent_projects.json')
  324. fp.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent_projects.json')
  327. fp = open(self.data_path + '/recent_projects.json', 'w')
  328. json.dump([], fp)
  329. fp.close()
  330. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  331. # This will fail under cx_freeze ...
  332. self.app_home = os.path.dirname(os.path.realpath(__file__))
  333. log.debug("Application path is " + self.app_home)
  334. log.debug("Started in " + os.getcwd())
  335. # cx_freeze workaround
  336. if os.path.isfile(self.app_home):
  337. self.app_home = os.path.dirname(self.app_home)
  338. os.chdir(self.app_home)
  339. # ############################################################################################################
  340. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  341. # ############################################################################################################
  342. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  343. self.defaults["root_folder_path"] = self.app_home
  344. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  345. if user_defaults:
  346. self.defaults.load(filename=current_defaults_path)
  347. if self.defaults['units'] == 'MM':
  348. self.decimals = int(self.defaults['decimals_metric'])
  349. else:
  350. self.decimals = int(self.defaults['decimals_inch'])
  351. if self.defaults["global_gray_icons"] is False:
  352. self.resource_location = 'assets/resources'
  353. else:
  354. self.resource_location = 'assets/resources/dark_resources'
  355. self.current_units = self.defaults['units']
  356. # ###########################################################################################################
  357. # #################################### SETUP OBJECT CLASSES #################################################
  358. # ###########################################################################################################
  359. self.setup_obj_classes()
  360. # ###########################################################################################################
  361. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  362. # ###########################################################################################################
  363. self.pool = Pool()
  364. # ###########################################################################################################
  365. # ###################################### Clear GUI Settings - once at first start ###########################
  366. # ###########################################################################################################
  367. if self.defaults["first_run"] is True:
  368. # on first run clear the previous QSettings, therefore clearing the GUI settings
  369. qsettings = QSettings("Open Source", "FlatCAM")
  370. for key in qsettings.allKeys():
  371. qsettings.remove(key)
  372. # This will write the setting to the platform specific storage.
  373. del qsettings
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  409. if theme_settings.contains("theme"):
  410. theme = theme_settings.value('theme', type=str)
  411. else:
  412. theme = 'white'
  413. if self.defaults["global_cursor_color_enabled"]:
  414. self.cursor_color_3D = self.defaults["global_cursor_color"]
  415. else:
  416. if theme == 'white':
  417. self.cursor_color_3D = 'black'
  418. else:
  419. self.cursor_color_3D = 'gray'
  420. # update the defaults dict with the setting in QSetting
  421. self.defaults['global_theme'] = theme
  422. self.ui = MainGUI(self)
  423. # set FlatCAM units in the Status bar
  424. self.set_screen_units(self.defaults['units'])
  425. # ###########################################################################################################
  426. # ########################################### AUTOSAVE SETUP ################################################
  427. # ###########################################################################################################
  428. self.block_autosave = False
  429. self.autosave_timer = QtCore.QTimer(self)
  430. self.save_project_auto_update()
  431. self.autosave_timer.timeout.connect(self.save_project_auto)
  432. # ###########################################################################################################
  433. # #################################### LOAD PREPROCESSORS ###################################################
  434. # ###########################################################################################################
  435. # ----------------------------------------- WARNING --------------------------------------------------------
  436. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  437. # That's because the number of preprocessors can vary and here the comboboxes are populated
  438. # -----------------------------------------------------------------------------------------------------------
  439. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  440. # the preprocessor file
  441. self.preprocessors = load_preprocessors(self)
  442. # make sure that always the 'default' preprocessor is the first item in the dictionary
  443. if 'default' in self.preprocessors.keys():
  444. new_ppp_dict = {}
  445. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  446. default_pp = self.preprocessors.pop('default')
  447. new_ppp_dict['default'] = default_pp
  448. # then add the rest of the keys
  449. for name, val_class in self.preprocessors.items():
  450. new_ppp_dict[name] = val_class
  451. # and now put back the ordered dict with 'default' key first
  452. self.preprocessors = new_ppp_dict
  453. # populate the Preprocessor ComboBoxes in the PREFERENCES
  454. for name in list(self.preprocessors.keys()):
  455. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  456. if name.partition('_')[0] == 'Paste':
  457. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  458. continue
  459. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  460. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  461. if name == 'hpgl':
  462. continue
  463. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  464. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  465. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  466. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  467. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  468. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  469. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  470. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  471. QtCore.Qt.ToolTipRole)
  472. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  473. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  474. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  475. QtCore.Qt.ToolTipRole)
  476. # ###########################################################################################################
  477. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  478. # ###########################################################################################################
  479. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  480. inform=self.inform)
  481. self.preferencesUiManager.defaults_write_form()
  482. # When the self.defaults dictionary changes will update the Preferences GUI forms
  483. self.defaults.set_change_callback(self.on_defaults_dict_change)
  484. # ###########################################################################################################
  485. # ##################################### FIRST RUN SECTION ###################################################
  486. # ################################ It's done only once after install #####################################
  487. # ###########################################################################################################
  488. if self.defaults["first_run"] is True:
  489. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  490. initial_lay = 'minimal'
  491. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  492. # Set the combobox in Preferences to the current layout
  493. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  494. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  495. # after the first run, this object should be False
  496. self.defaults["first_run"] = False
  497. self.preferencesUiManager.save_defaults(silent=True)
  498. # ###########################################################################################################
  499. # ############################################ Data #########################################################
  500. # ###########################################################################################################
  501. self.recent = []
  502. self.recent_projects = []
  503. self.clipboard = QtWidgets.QApplication.clipboard()
  504. self.project_filename = None
  505. self.toggle_units_ignore = False
  506. self.main_thread = QtWidgets.QApplication.instance().thread()
  507. # ###########################################################################################################
  508. # ########################################## LOAD LANGUAGES ################################################
  509. # ###########################################################################################################
  510. self.languages = fcTranslate.load_languages()
  511. for name in sorted(self.languages.values()):
  512. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  513. # ###########################################################################################################
  514. # ####################################### APPLY APP LANGUAGE ################################################
  515. # ###########################################################################################################
  516. ret_val = fcTranslate.apply_language('strings')
  517. if ret_val == "no language":
  518. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  519. log.debug("Could not find the Language files. The App strings are missing.")
  520. else:
  521. # make the current language the current selection on the language combobox
  522. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  523. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  524. # ###########################################################################################################
  525. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  526. # ###########################################################################################################
  527. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  528. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  529. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  530. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  531. self.defaults.propagate_defaults()
  532. # ###########################################################################################################
  533. # ######################################## UPDATE THE OPTIONS ###############################################
  534. # ###########################################################################################################
  535. self.options = LoudDict()
  536. # -----------------------------------------------------------------------------------------------------------
  537. # Update the self.options from the self.defaults
  538. # The self.defaults holds the application defaults while the self.options holds the object defaults
  539. # -----------------------------------------------------------------------------------------------------------
  540. # Copy app defaults to project options
  541. for def_key, def_val in self.defaults.items():
  542. self.options[def_key] = deepcopy(def_val)
  543. self.preferencesUiManager.show_preferences_gui()
  544. # ### End of Data ####
  545. # ###########################################################################################################
  546. # #################################### SETUP OBJECT COLLECTION ##############################################
  547. # ###########################################################################################################
  548. self.collection = ObjectCollection(app=self)
  549. self.ui.project_tab_layout.addWidget(self.collection.view)
  550. self.app_obj = AppObject(app=self)
  551. # ### Adjust tabs width ## ##
  552. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  553. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  554. self.collection.view.setMinimumWidth(290)
  555. self.log.debug("Finished creating Object Collection.")
  556. # ###########################################################################################################
  557. # ######################################## SETUP Plot Area ##################################################
  558. # ###########################################################################################################
  559. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  560. if self.defaults["global_graphic_engine"] == '3D':
  561. self.is_legacy = False
  562. else:
  563. self.is_legacy = True
  564. # Event signals disconnect id holders
  565. self.mp = None
  566. self.mm = None
  567. self.mr = None
  568. self.mdc = None
  569. self.mp_zc = None
  570. self.kp = None
  571. # Matplotlib axis
  572. self.axes = None
  573. if show_splash:
  574. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  575. "Canvas initialization started."),
  576. alignment=Qt.AlignBottom | Qt.AlignLeft,
  577. color=QtGui.QColor("gray"))
  578. start_plot_time = time.time() # debug
  579. self.plotcanvas = None
  580. self.app_cursor = None
  581. self.hover_shapes = None
  582. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  583. # setup the PlotCanvas
  584. self.on_plotcanvas_setup()
  585. end_plot_time = time.time()
  586. self.used_time = end_plot_time - start_plot_time
  587. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  588. if show_splash:
  589. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  590. "Canvas initialization started.\n"
  591. "Canvas initialization finished in"), '%.2f' % self.used_time),
  592. alignment=Qt.AlignBottom | Qt.AlignLeft,
  593. color=QtGui.QColor("gray"))
  594. self.ui.splitter.setStretchFactor(1, 2)
  595. # ###########################################################################################################
  596. # ############################################### SYS TRAY ##################################################
  597. # ###########################################################################################################
  598. if self.defaults["global_systray_icon"]:
  599. self.parent_w = QtWidgets.QWidget()
  600. if self.cmd_line_headless == 1:
  601. self.trayIcon = FlatCAMSystemTray(app=self,
  602. icon=QtGui.QIcon(self.resource_location +
  603. '/flatcam_icon32_green.png'),
  604. headless=True,
  605. parent=self.parent_w)
  606. else:
  607. self.trayIcon = FlatCAMSystemTray(app=self,
  608. icon=QtGui.QIcon(self.resource_location +
  609. '/flatcam_icon32_green.png'),
  610. parent=self.parent_w)
  611. # ###########################################################################################################
  612. # ############################################### Worker SETUP ##############################################
  613. # ###########################################################################################################
  614. if self.defaults["global_worker_number"]:
  615. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  616. else:
  617. self.workers = WorkerStack(workers_number=2)
  618. self.worker_task.connect(self.workers.add_task)
  619. self.log.debug("Finished creating Workers crew.")
  620. # ###########################################################################################################
  621. # ############################################# Activity Monitor ###########################################
  622. # ###########################################################################################################
  623. # self.activity_view = FlatCAMActivityView(app=self)
  624. # self.ui.infobar.addWidget(self.activity_view)
  625. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  626. # ###########################################################################################################
  627. # ############################################# Signal handling #############################################
  628. # ###########################################################################################################
  629. # ########################################## Custom signals ################################################
  630. # signal for displaying messages in status bar
  631. self.inform[str].connect(self.info)
  632. self.inform[str, bool].connect(self.info)
  633. # signal for displaying messages in the shell
  634. self.inform_shell.connect(self.info_shell)
  635. # signal to be called when the app is quiting
  636. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  637. self.message.connect(lambda: message_dialog(parent=self.ui))
  638. # self.progress.connect(self.set_progress_bar)
  639. # signals emitted when file state change
  640. self.file_opened.connect(self.register_recent)
  641. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  642. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  643. # ########################################## Standard signals ###############################################
  644. # ### Menu
  645. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  646. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  647. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  648. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  649. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  650. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  651. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  652. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  653. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  654. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  655. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  656. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  657. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  658. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  659. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  660. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  661. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  662. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  663. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  664. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  665. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  666. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  667. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  668. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  669. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  670. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  671. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  672. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  673. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  674. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  675. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  676. self.ui.menufile_exit.triggered.connect(self.final_save)
  677. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  678. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  679. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  680. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  681. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  682. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  683. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  684. self.ui.menueditdelete.triggered.connect(self.on_delete)
  685. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  686. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  687. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  688. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  689. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  690. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  691. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  692. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  693. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  694. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  695. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  696. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  697. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  698. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  699. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  700. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  701. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  702. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  703. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  704. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  705. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  706. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  707. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  708. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  709. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  710. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  711. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  712. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  713. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  714. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  715. self.ui.menuview_replot.triggered.connect(self.plot_all)
  716. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  717. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  718. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  719. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  720. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  721. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  722. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  723. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  724. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  725. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  726. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  727. self.ui.menuhelp_about.triggered.connect(self.on_about)
  728. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  729. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  730. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  731. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  732. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  733. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  734. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  735. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  736. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  737. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  738. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  739. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  740. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  741. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  742. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  743. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  744. # ToolBar signals
  745. self.connect_toolbar_signals(ui=self.ui)
  746. # Context Menu
  747. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  748. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  749. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  750. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  751. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  752. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  753. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  754. self.ui.clearplot.triggered.connect(self.clear_plots)
  755. self.ui.replot.triggered.connect(self.plot_all)
  756. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  757. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  758. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  759. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  760. self.ui.popmenu_move.triggered.connect(self.obj_move)
  761. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  762. # Project Context Menu -> Color Setting
  763. for act in self.ui.menuprojectcolor.actions():
  764. act.triggered.connect(self.on_set_color_action_triggered)
  765. # ###########################################################################################################
  766. # #################################### GUI PREFERENCES SIGNALS ##############################################
  767. # ###########################################################################################################
  768. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  769. lambda: self.on_toggle_units(no_pref=False))
  770. # ##################################### Workspace Setting Signals ###########################################
  771. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  772. self.on_workspace_modified)
  773. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  774. self.on_workspace_modified
  775. )
  776. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  777. # ###########################################################################################################
  778. # ######################################## GUI SETTINGS SIGNALS #############################################
  779. # ###########################################################################################################
  780. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  781. # ######################################## Tools related signals ############################################
  782. # portability changed signal
  783. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  784. # Object list
  785. self.object_status_changed.connect(self.collection.on_collection_updated)
  786. # when there are arguments at application startup this get launched
  787. self.args_at_startup[list].connect(self.on_startup_args)
  788. # ###########################################################################################################
  789. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  790. # ###########################################################################################################
  791. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  792. lambda: self.restore_extensions(ext_type='excellon'))
  793. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  794. lambda: self.restore_extensions(ext_type='gcode'))
  795. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  796. lambda: self.restore_extensions(ext_type='gerber'))
  797. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  798. lambda: self.delete_all_extensions(ext_type='excellon'))
  799. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  800. lambda: self.delete_all_extensions(ext_type='gcode'))
  801. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  802. lambda: self.delete_all_extensions(ext_type='gerber'))
  803. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  804. lambda: self.add_extension(ext_type='excellon'))
  805. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  806. lambda: self.add_extension(ext_type='gcode'))
  807. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  808. lambda: self.add_extension(ext_type='gerber'))
  809. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  810. lambda: self.del_extension(ext_type='excellon'))
  811. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  812. lambda: self.del_extension(ext_type='gcode'))
  813. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  814. lambda: self.del_extension(ext_type='gerber'))
  815. # connect the 'Apply' buttons from the Preferences/File Associations
  816. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  817. lambda: self.on_register_files(obj_type='excellon'))
  818. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  819. lambda: self.on_register_files(obj_type='gcode'))
  820. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  821. lambda: self.on_register_files(obj_type='gerber'))
  822. # ###########################################################################################################
  823. # ########################################### KEYWORDS SIGNALS ##############################################
  824. # ###########################################################################################################
  825. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  826. lambda: self.restore_extensions(ext_type='keyword'))
  827. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  828. lambda: self.delete_all_extensions(ext_type='keyword'))
  829. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  830. lambda: self.add_extension(ext_type='keyword'))
  831. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='keyword'))
  833. # ###########################################################################################################
  834. # ########################################### GUI SIGNALS ###################################################
  835. # ###########################################################################################################
  836. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  837. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  838. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  839. # ###########################################################################################################
  840. # ####################################### VARIOUS SIGNALS ###################################################
  841. # ###########################################################################################################
  842. # connect the abort_all_tasks related slots to the related signals
  843. self.proc_container.idle_flag.connect(self.app_is_idle)
  844. # signal emitted when a tab is closed in the Plot Area
  845. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  846. # signal to close the application
  847. self.close_app_signal.connect(self.kill_app)
  848. # ################################# FINISHED CONNECTING SIGNALS #############################################
  849. # ###########################################################################################################
  850. # ###########################################################################################################
  851. # ###########################################################################################################
  852. self.log.debug("Finished connecting Signals.")
  853. # ###########################################################################################################
  854. # ########################################## Other setups ###################################################
  855. # ###########################################################################################################
  856. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  857. # depending on from where those tools are called different actions can be done
  858. self.call_source = 'app'
  859. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  860. self.tool_tab_locked = False
  861. # decide if to show or hide the Notebook side of the screen at startup
  862. if self.defaults["global_project_at_startup"] is True:
  863. self.ui.splitter.setSizes([1, 1])
  864. else:
  865. self.ui.splitter.setSizes([0, 1])
  866. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  867. self.setup_component_editor()
  868. # ###########################################################################################################
  869. # ####################################### Auto-complete KEYWORDS ############################################
  870. # ###########################################################################################################
  871. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  872. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  873. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  874. 'export_exc',
  875. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  876. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  877. 'interiors', 'isolate', 'join_excellon',
  878. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  879. 'mirror', 'ncc',
  880. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  881. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  882. 'options', 'origin',
  883. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  884. 'save', 'save_project',
  885. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  886. 'skew', 'subtract_poly', 'subtract_rectangle',
  887. 'version', 'write_gcode'
  888. ]
  889. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  890. 'Paste_1',
  891. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  892. 'Toolchange_manual', 'True', 'Users',
  893. 'all', 'auto', 'axis',
  894. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  895. 'contour', 'default',
  896. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  897. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  898. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  899. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  900. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  901. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  902. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  903. 'spacing_columns',
  904. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  905. 'toolchange_xy', 'toolchangez', 'travelz',
  906. 'tooldia', 'use_threads', 'value',
  907. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  908. ]
  909. self.tcl_keywords = [
  910. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  911. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  912. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  913. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  914. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  915. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  916. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  917. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  918. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  919. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  920. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  921. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  922. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  923. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  924. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  925. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  926. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  927. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  928. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  929. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  930. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  931. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  932. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  933. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  934. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  935. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  936. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  937. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  938. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  939. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  940. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  941. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  942. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  943. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  944. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  945. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  946. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  947. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  948. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  949. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  950. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  951. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  952. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  953. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  954. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  955. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  956. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  957. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  958. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  959. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  960. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  961. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  962. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  963. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  964. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  965. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  966. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  967. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  968. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  969. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  970. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  971. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  972. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  973. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  974. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  975. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  976. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  977. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  978. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  979. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  980. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  981. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  982. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  983. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  984. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  985. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  986. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  987. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  988. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  989. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  990. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  991. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  992. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  993. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  994. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  995. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  996. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  997. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  998. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  999. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1000. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1001. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1002. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1003. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1004. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1005. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1006. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1007. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1008. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1009. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1010. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1011. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1012. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1013. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1014. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1015. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1016. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1017. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1018. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1019. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1020. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1021. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1022. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1023. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1024. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1025. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1026. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1027. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1028. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1029. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1030. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1031. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1032. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1033. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1034. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1035. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1036. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1037. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1038. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1039. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1040. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1041. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1042. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1043. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1044. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1045. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1046. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1047. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1048. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1049. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1050. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1051. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1052. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1053. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1054. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1055. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1056. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1057. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1058. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1059. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1060. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1061. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1062. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1063. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1064. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1065. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1066. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1067. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1068. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1069. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1070. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1071. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1072. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1073. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1074. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1075. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1076. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1077. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1078. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1079. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1080. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1081. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1082. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1083. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1084. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1085. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1086. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1087. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1088. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1089. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1090. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1091. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1092. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1093. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1094. ]
  1095. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1096. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1097. # ###########################################################################################################
  1098. # ########################################## Tools and Plugins ##############################################
  1099. # ###########################################################################################################
  1100. self.shell = None
  1101. self.dblsidedtool = None
  1102. self.distance_tool = None
  1103. self.distance_min_tool = None
  1104. self.panelize_tool = None
  1105. self.film_tool = None
  1106. self.paste_tool = None
  1107. self.calculator_tool = None
  1108. self.rules_tool = None
  1109. self.sub_tool = None
  1110. self.move_tool = None
  1111. self.cutout_tool = None
  1112. self.ncclear_tool = None
  1113. self.paint_tool = None
  1114. self.isolation_tool = None
  1115. self.drilling_tool = None
  1116. self.optimal_tool = None
  1117. self.transform_tool = None
  1118. self.properties_tool = None
  1119. self.pdf_tool = None
  1120. self.image_tool = None
  1121. self.pcb_wizard_tool = None
  1122. self.cal_exc_tool = None
  1123. self.qrcode_tool = None
  1124. self.copper_thieving_tool = None
  1125. self.fiducial_tool = None
  1126. self.edrills_tool = None
  1127. self.align_objects_tool = None
  1128. self.punch_tool = None
  1129. self.invert_tool = None
  1130. self.corners_tool = None
  1131. self.etch_tool = None
  1132. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1133. try:
  1134. self.install_tools()
  1135. except AttributeError as e:
  1136. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1137. # ###########################################################################################################
  1138. # ############################################ SETUP RECENT ITEMS ###########################################
  1139. # ###########################################################################################################
  1140. self.setup_recent_items()
  1141. # ###########################################################################################################
  1142. # ######################################### BookMarks Manager ###############################################
  1143. # ###########################################################################################################
  1144. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1145. self.install_bookmarks()
  1146. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1147. # ###########################################################################################################
  1148. # ########################################### Tools Database ################################################
  1149. # ###########################################################################################################
  1150. self.tools_db_tab = None
  1151. # ### System Font Parsing ###
  1152. # self.f_parse = ParseFont(self)
  1153. # self.parse_system_fonts()
  1154. # ###########################################################################################################
  1155. # ############################################## Shell SETUP ################################################
  1156. # ###########################################################################################################
  1157. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1158. if self.defaults["global_shell_at_startup"]:
  1159. self.ui.shell_dock.show()
  1160. else:
  1161. self.ui.shell_dock.hide()
  1162. # ###########################################################################################################
  1163. # ######################################### Check for updates ###############################################
  1164. # ###########################################################################################################
  1165. # Separate thread (Not worker)
  1166. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1167. if (self.beta is False or self.beta is None) and \
  1168. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1169. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1170. # self.thr2 = QtCore.QThread()
  1171. self.worker_task.emit({'fcn': self.version_check,
  1172. 'params': []})
  1173. # self.thr2.start(QtCore.QThread.LowPriority)
  1174. # ###########################################################################################################
  1175. # ##################################### Register files with FlatCAM; #######################################
  1176. # ################################### It works only for Windows for now ####################################
  1177. # ###########################################################################################################
  1178. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1179. self.on_register_files()
  1180. # ###########################################################################################################
  1181. # ######################################## Variables for global usage #######################################
  1182. # ###########################################################################################################
  1183. # hold the App units
  1184. self.units = 'MM'
  1185. # coordinates for relative position display
  1186. self.rel_point1 = (0, 0)
  1187. self.rel_point2 = (0, 0)
  1188. # variable to store coordinates
  1189. self.pos = (0, 0)
  1190. self.pos_canvas = (0, 0)
  1191. self.pos_jump = (0, 0)
  1192. # variable to store mouse coordinates
  1193. self.mouse = [0, 0]
  1194. # variable to store the delta positions on cavnas
  1195. self.dx = 0
  1196. self.dy = 0
  1197. # decide if we have a double click or single click
  1198. self.doubleclick = False
  1199. # store here the is_dragging value
  1200. self.event_is_dragging = False
  1201. # variable to store if a command is active (then the var is not None) and which one it is
  1202. self.command_active = None
  1203. # variable to store the status of moving selection action
  1204. # None value means that it's not an selection action
  1205. # True value = a selection from left to right
  1206. # False value = a selection from right to left
  1207. self.selection_type = None
  1208. # List to store the objects that are currently loaded in FlatCAM
  1209. # This list is updated on each object creation or object delete
  1210. self.all_objects_list = []
  1211. self.objects_under_the_click_list = []
  1212. # List to store the objects that are selected
  1213. self.sel_objects_list = []
  1214. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1215. self.key_modifiers = None
  1216. # Variable to store the status of the code editor
  1217. self.toggle_codeeditor = False
  1218. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1219. self.click_noproject = False
  1220. self.cursor = None
  1221. # Variable to store the GCODE that was edited
  1222. self.gcode_edited = ""
  1223. self.text_editor_tab = None
  1224. # reference for the self.ui.code_editor
  1225. self.reference_code_editor = None
  1226. self.script_code = ''
  1227. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1228. self.tools_db_changed_flag = False
  1229. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1230. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1231. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1232. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1233. 'tsm']
  1234. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1235. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1236. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1237. 'sbp', 'tap', 'xpi']
  1238. self.svg_list = ['svg']
  1239. self.dxf_list = ['dxf']
  1240. self.pdf_list = ['pdf']
  1241. self.prj_list = ['flatprj']
  1242. self.conf_list = ['flatconfig']
  1243. # last used filters
  1244. self.last_op_gerber_filter = None
  1245. self.last_op_excellon_filter = None
  1246. self.last_op_gcode_filter = None
  1247. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1248. # flag for polygons not cleared
  1249. self.poly_not_cleared = False
  1250. # VisPy visuals
  1251. self.isHovering = False
  1252. self.notHovering = True
  1253. # Window geometry
  1254. self.x_pos = None
  1255. self.y_pos = None
  1256. self.width = None
  1257. self.height = None
  1258. # when True, the app has to return from any thread
  1259. self.abort_flag = False
  1260. # set the value used in the Windows Title
  1261. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1262. # this holds a widget that is installed in the Plot Area when View Source option is used
  1263. self.source_editor_tab = None
  1264. self.pagesize = {}
  1265. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1266. # VisPy visuals
  1267. if self.is_legacy is False:
  1268. try:
  1269. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1270. except AttributeError:
  1271. self.tool_shapes = None
  1272. else:
  1273. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1274. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1275. # used in the delayed shutdown self.start_delayed_quit() method
  1276. self.save_timer = None
  1277. # ###########################################################################################################
  1278. # ################################## ADDING FlatCAM EDITORS section #########################################
  1279. # ###########################################################################################################
  1280. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1281. # at the first launch of the App , the editors will not be functional.
  1282. try:
  1283. self.geo_editor = AppGeoEditor(self)
  1284. except Exception as es:
  1285. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1286. try:
  1287. self.exc_editor = AppExcEditor(self)
  1288. except Exception as es:
  1289. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1290. try:
  1291. self.grb_editor = AppGerberEditor(self)
  1292. except Exception as es:
  1293. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1294. self.log.debug("Finished adding FlatCAM Editor's.")
  1295. self.set_ui_title(name=_("New Project - Not saved"))
  1296. current_platform = platform.architecture()[0]
  1297. if current_platform != '64bit':
  1298. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1299. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1300. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1301. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1302. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1303. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1304. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1305. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1306. # ###########################################################################################################
  1307. # ########################################### EXCLUSION AREAS ###############################################
  1308. # ###########################################################################################################
  1309. self.exc_areas = ExclusionAreas(app=self)
  1310. # ###########################################################################################################
  1311. # ##################################### Finished the CONSTRUCTOR ############################################
  1312. # ###########################################################################################################
  1313. App.log.debug("END of constructor. Releasing control.")
  1314. # ###########################################################################################################
  1315. # ########################################## SHOW GUI #######################################################
  1316. # ###########################################################################################################
  1317. # if the app is not started as headless, show it
  1318. if self.cmd_line_headless != 1:
  1319. if show_splash:
  1320. # finish the splash
  1321. self.splash.finish(self.ui)
  1322. mgui_settings = QSettings("Open Source", "FlatCAM")
  1323. if mgui_settings.contains("maximized_gui"):
  1324. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1325. if maximized_ui is True:
  1326. self.ui.showMaximized()
  1327. else:
  1328. self.ui.show()
  1329. else:
  1330. self.ui.show()
  1331. if self.defaults["global_systray_icon"]:
  1332. self.trayIcon.show()
  1333. else:
  1334. log.warning("******************* RUNNING HEADLESS *******************")
  1335. # ###########################################################################################################
  1336. # ######################################## START-UP ARGUMENTS ###############################################
  1337. # ###########################################################################################################
  1338. # test if the program was started with a script as parameter
  1339. if self.cmd_line_shellvar:
  1340. try:
  1341. cnt = 0
  1342. command_tcl = 0
  1343. for i in self.cmd_line_shellvar.split(','):
  1344. if i is not None:
  1345. # noinspection PyBroadException
  1346. try:
  1347. command_tcl = eval(i)
  1348. except Exception:
  1349. command_tcl = i
  1350. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1351. cnt += 1
  1352. # if there are Windows paths then replace the path separator with a Unix like one
  1353. if sys.platform == 'win32':
  1354. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1355. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1356. except Exception as ext:
  1357. print("ERROR: ", ext)
  1358. sys.exit(2)
  1359. if self.cmd_line_shellfile:
  1360. if self.cmd_line_headless != 1:
  1361. if self.ui.shell_dock.isHidden():
  1362. self.ui.shell_dock.show()
  1363. try:
  1364. with open(self.cmd_line_shellfile, "r") as myfile:
  1365. # if show_splash:
  1366. # self.splash.showMessage('%s: %ssec\n%s' % (
  1367. # _("Canvas initialization started.\n"
  1368. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1369. # _("Executing Tcl Script ...")),
  1370. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1371. # color=QtGui.QColor("gray"))
  1372. cmd_line_shellfile_text = myfile.read()
  1373. if self.cmd_line_headless != 1:
  1374. self.shell.exec_command(cmd_line_shellfile_text)
  1375. else:
  1376. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1377. except Exception as ext:
  1378. print("ERROR: ", ext)
  1379. sys.exit(2)
  1380. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1381. # the path/file_name must be enclosed in quotes if it contain spaces
  1382. if App.args:
  1383. self.args_at_startup.emit(App.args)
  1384. if self.defaults.old_defaults_found is True:
  1385. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1386. "Please reboot the application to update."))
  1387. self.defaults.old_defaults_found = False
  1388. # ######################################### INIT FINISHED #######################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. @staticmethod
  1395. def copy_and_overwrite(from_path, to_path):
  1396. """
  1397. From here:
  1398. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1399. :param from_path: source path
  1400. :param to_path: destination path
  1401. :return: None
  1402. """
  1403. if os.path.exists(to_path):
  1404. shutil.rmtree(to_path)
  1405. try:
  1406. shutil.copytree(from_path, to_path)
  1407. except FileNotFoundError:
  1408. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1409. shutil.copytree(from_new_path, to_path)
  1410. def on_startup_args(self, args, silent=False):
  1411. """
  1412. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1413. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1414. :param args: a list containing the application args at startup
  1415. :return: None
  1416. """
  1417. if args is not None:
  1418. args_to_process = args
  1419. else:
  1420. args_to_process = App.args
  1421. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1422. for argument in args_to_process:
  1423. if '.FlatPrj'.lower() in argument.lower():
  1424. try:
  1425. project_name = str(argument)
  1426. if project_name == "":
  1427. if silent is False:
  1428. self.inform.emit(_("Cancelled."))
  1429. else:
  1430. # self.open_project(project_name)
  1431. run_from_arg = True
  1432. # self.worker_task.emit({'fcn': self.open_project,
  1433. # 'params': [project_name, run_from_arg]})
  1434. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1435. except Exception as e:
  1436. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1437. elif '.FlatConfig'.lower() in argument.lower():
  1438. try:
  1439. file_name = str(argument)
  1440. if file_name == "":
  1441. if silent is False:
  1442. self.inform.emit(_("Open Config file failed."))
  1443. else:
  1444. run_from_arg = True
  1445. # self.worker_task.emit({'fcn': self.open_config_file,
  1446. # 'params': [file_name, run_from_arg]})
  1447. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1448. except Exception as e:
  1449. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1450. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1451. try:
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open Script file failed."))
  1456. else:
  1457. if silent is False:
  1458. self.on_fileopenscript(name=file_name)
  1459. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1460. self.on_filerunscript(name=file_name)
  1461. except Exception as e:
  1462. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1463. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1464. log.debug("App.on_startup_args() --> Quit event.")
  1465. sys.exit()
  1466. elif 'save'.lower() in argument.lower():
  1467. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1468. self.preferencesUiManager.save_defaults()
  1469. else:
  1470. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1471. proc_arg = argument.lower()
  1472. for ext in exc_list:
  1473. proc_ext = ext.replace(' ', '')
  1474. proc_ext = '.%s' % proc_ext
  1475. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1476. file_name = str(argument)
  1477. if file_name == "":
  1478. if silent is False:
  1479. self.inform.emit(_("Open Excellon file failed."))
  1480. else:
  1481. self.on_fileopenexcellon(name=file_name, signal=None)
  1482. return
  1483. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1484. for ext in gco_list:
  1485. proc_ext = ext.replace(' ', '')
  1486. proc_ext = '.%s' % proc_ext
  1487. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1488. file_name = str(argument)
  1489. if file_name == "":
  1490. if silent is False:
  1491. self.inform.emit(_("Open GCode file failed."))
  1492. else:
  1493. self.on_fileopengcode(name=file_name, signal=None)
  1494. return
  1495. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1496. for ext in grb_list:
  1497. proc_ext = ext.replace(' ', '')
  1498. proc_ext = '.%s' % proc_ext
  1499. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1500. file_name = str(argument)
  1501. if file_name == "":
  1502. if silent is False:
  1503. self.inform.emit(_("Open Gerber file failed."))
  1504. else:
  1505. self.on_fileopengerber(name=file_name, signal=None)
  1506. return
  1507. # if it reached here without already returning then the app was registered with a file that it does not
  1508. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1509. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1510. # for arg in args_to_process:
  1511. # if 'FlatCAM.exe' in arg:
  1512. # continue
  1513. # else:
  1514. # sys.exit(2)
  1515. def set_ui_title(self, name):
  1516. """
  1517. Sets the title of the main window.
  1518. :param name: String that store the project path and project name
  1519. :return: None
  1520. """
  1521. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1522. (self.version,
  1523. ('BETA' if self.beta else ''),
  1524. platform.architecture()[0],
  1525. self.engine,
  1526. name)
  1527. )
  1528. def on_app_restart(self):
  1529. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1530. # be left in the SySTray
  1531. try:
  1532. self.trayIcon.hide()
  1533. except Exception:
  1534. pass
  1535. fcTranslate.restart_program(app=self)
  1536. def clear_pool(self):
  1537. """
  1538. Clear the multiprocessing pool and calls garbage collector.
  1539. :return: None
  1540. """
  1541. self.pool.close()
  1542. self.pool = Pool()
  1543. self.pool_recreated.emit(self.pool)
  1544. gc.collect()
  1545. def install_tools(self):
  1546. """
  1547. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1548. Instantiation of the Tools classes.
  1549. The order that the tools are installed is important as they can depend on each other install position.
  1550. :return: None
  1551. """
  1552. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1553. self.shell = FCShell(app=self, version=self.version)
  1554. self.distance_tool = Distance(self)
  1555. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=False)
  1558. self.distance_min_tool = DistanceMin(self)
  1559. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1560. pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=True)
  1563. self.dblsidedtool = DblSidedTool(self)
  1564. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1565. self.cal_exc_tool = ToolCalibration(self)
  1566. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1567. before=self.dblsidedtool.menuAction,
  1568. separator=False)
  1569. self.align_objects_tool = AlignObjects(self)
  1570. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1571. self.edrills_tool = ToolExtractDrills(self)
  1572. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1573. self.panelize_tool = Panelize(self)
  1574. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1575. self.film_tool = Film(self)
  1576. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1577. self.paste_tool = SolderPaste(self)
  1578. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1579. self.calculator_tool = ToolCalculator(self)
  1580. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1581. self.sub_tool = ToolSub(self)
  1582. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1583. pos=self.ui.menutool, separator=True)
  1584. self.rules_tool = RulesCheck(self)
  1585. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1586. pos=self.ui.menutool, separator=False)
  1587. self.optimal_tool = ToolOptimal(self)
  1588. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1589. pos=self.ui.menutool, separator=True)
  1590. self.move_tool = ToolMove(self)
  1591. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1592. before=self.ui.menueditorigin, separator=True)
  1593. self.cutout_tool = CutOut(self)
  1594. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1595. before=self.sub_tool.menuAction)
  1596. self.ncclear_tool = NonCopperClear(self)
  1597. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1598. before=self.sub_tool.menuAction, separator=True)
  1599. self.paint_tool = ToolPaint(self)
  1600. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1601. before=self.sub_tool.menuAction, separator=True)
  1602. self.isolation_tool = ToolIsolation(self)
  1603. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1604. before=self.sub_tool.menuAction, separator=True)
  1605. self.drilling_tool = ToolDrilling(self)
  1606. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1607. before=self.sub_tool.menuAction, separator=True)
  1608. self.copper_thieving_tool = ToolCopperThieving(self)
  1609. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1610. pos=self.ui.menutool)
  1611. self.fiducial_tool = ToolFiducials(self)
  1612. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1613. pos=self.ui.menutool)
  1614. self.qrcode_tool = QRCode(self)
  1615. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1616. pos=self.ui.menutool)
  1617. self.punch_tool = ToolPunchGerber(self)
  1618. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1619. self.invert_tool = ToolInvertGerber(self)
  1620. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1621. self.corners_tool = ToolCorners(self)
  1622. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1623. self.etch_tool = ToolEtchCompensation(self)
  1624. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1625. self.transform_tool = ToolTransform(self)
  1626. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1627. pos=self.ui.menuoptions, separator=True)
  1628. self.properties_tool = Properties(self)
  1629. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1630. pos=self.ui.menuoptions)
  1631. self.pdf_tool = ToolPDF(self)
  1632. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1633. pos=self.ui.menufileimport,
  1634. separator=True)
  1635. self.image_tool = ToolImage(self)
  1636. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1637. pos=self.ui.menufileimport,
  1638. separator=True)
  1639. self.pcb_wizard_tool = PcbWizard(self)
  1640. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1641. pos=self.ui.menufileimport)
  1642. self.log.debug("Tools are installed.")
  1643. def remove_tools(self):
  1644. """
  1645. Will remove all the actions in the Tool menu.
  1646. :return: None
  1647. """
  1648. for act in self.ui.menutool.actions():
  1649. self.ui.menutool.removeAction(act)
  1650. def init_tools(self):
  1651. """
  1652. Initialize the Tool tab in the notebook side of the central widget.
  1653. Remove the actions in the Tools menu.
  1654. Instantiate again the FlatCAM tools (plugins).
  1655. All this is required when changing the layout: standard, compact etc.
  1656. :return: None
  1657. """
  1658. log.debug("init_tools()")
  1659. # delete the data currently in the Tools Tab and the Tab itself
  1660. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1661. if widget is not None:
  1662. widget.deleteLater()
  1663. self.ui.notebook.removeTab(2)
  1664. # rebuild the Tools Tab
  1665. self.ui.tool_tab = QtWidgets.QWidget()
  1666. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1667. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1668. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1669. self.ui.tool_scroll_area = VerticalScrollArea()
  1670. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1671. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1672. # first remove all of them
  1673. self.remove_tools()
  1674. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1675. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1676. '&Command Line\tS')
  1677. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1678. # third install all of them
  1679. try:
  1680. self.install_tools()
  1681. except AttributeError:
  1682. pass
  1683. self.log.debug("Tools are initialized.")
  1684. # def parse_system_fonts(self):
  1685. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1686. # 'params': []})
  1687. def connect_tools_signals_to_toolbar(self, ui):
  1688. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1689. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1690. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1691. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1692. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1693. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1694. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1695. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1696. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1697. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1698. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1699. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1700. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1701. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1702. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1703. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1704. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1705. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1706. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1707. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1708. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1709. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1710. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1711. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1712. def connect_toolbar_signals(self, ui):
  1713. """
  1714. Reconnect the signals to the actions in the toolbar.
  1715. This has to be done each time after the FlatCAM tools are removed/installed.
  1716. :return: None
  1717. """
  1718. # Toolbar
  1719. # File Toolbar Signals
  1720. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1721. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1722. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1723. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1724. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1725. # View Toolbar Signals
  1726. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1727. ui.replot_btn.triggered.connect(self.plot_all)
  1728. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1729. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1730. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1731. # Edit Toolbar Signals
  1732. ui.editgeo_btn.triggered.connect(self.object2editor)
  1733. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1734. ui.copy_btn.triggered.connect(self.on_copy_command)
  1735. ui.delete_btn.triggered.connect(self.on_delete)
  1736. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1737. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1738. ui.origin_btn.triggered.connect(self.on_set_origin)
  1739. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1740. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1741. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1742. # Scripting Toolbar Signals
  1743. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1744. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1745. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1746. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1747. # Tools Toolbar Signals
  1748. try:
  1749. self.connect_tools_signals_to_toolbar(ui=ui)
  1750. except Exception as err:
  1751. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1752. def object2editor(self):
  1753. """
  1754. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1755. :return: None
  1756. """
  1757. self.defaults.report_usage("object2editor()")
  1758. # disable the objects menu as it may interfere with the appEditors
  1759. self.ui.menuobjects.setDisabled(True)
  1760. edited_object = self.collection.get_active()
  1761. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1762. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1763. pass
  1764. else:
  1765. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1766. return
  1767. if isinstance(edited_object, GeometryObject):
  1768. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1769. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1770. # we set the notebook to hidden
  1771. # self.ui.splitter.setSizes([0, 1])
  1772. if edited_object.multigeo is True:
  1773. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1774. if len(sel_rows) > 1:
  1775. self.inform.emit('[WARNING_NOTCL] %s' %
  1776. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1777. "is not possible.\n"
  1778. "Edit only one geometry at a time."))
  1779. if not sel_rows:
  1780. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1781. return
  1782. # determine the tool dia of the selected tool
  1783. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1784. # now find the key in the edited_object.tools that has this tooldia
  1785. multi_tool = 1
  1786. for tool in edited_object.tools:
  1787. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1788. multi_tool = tool
  1789. break
  1790. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1791. else:
  1792. self.geo_editor.edit_fcgeometry(edited_object)
  1793. # set call source to the Editor we go into
  1794. self.call_source = 'geo_editor'
  1795. elif isinstance(edited_object, ExcellonObject):
  1796. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1797. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1798. if self.ui.splitter.sizes()[0] == 0:
  1799. self.ui.splitter.setSizes([1, 1])
  1800. self.exc_editor.edit_fcexcellon(edited_object)
  1801. # set call source to the Editor we go into
  1802. self.call_source = 'exc_editor'
  1803. elif isinstance(edited_object, GerberObject):
  1804. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1805. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1806. if self.ui.splitter.sizes()[0] == 0:
  1807. self.ui.splitter.setSizes([1, 1])
  1808. self.grb_editor.edit_fcgerber(edited_object)
  1809. # set call source to the Editor we go into
  1810. self.call_source = 'grb_editor'
  1811. # reset the following variables so the UI is built again after edit
  1812. edited_object.ui_build = False
  1813. elif isinstance(edited_object, CNCJobObject):
  1814. if self.ui.splitter.sizes()[0] == 0:
  1815. self.ui.splitter.setSizes([1, 1])
  1816. edited_object.on_edit_code_click()
  1817. return
  1818. # make sure that we can't select another object while in Editor Mode:
  1819. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1820. self.ui.project_frame.setDisabled(True)
  1821. # delete any selection shape that might be active as they are not relevant in Editor
  1822. self.delete_selection_shape()
  1823. # hide the Tools Toolbar
  1824. tools_tb = self.ui.toolbartools
  1825. if tools_tb.isVisible():
  1826. tools_tb.hide()
  1827. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1828. self.ui.plot_tab_area.protectTab(0)
  1829. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1830. self.should_we_save = True
  1831. def editor2object(self, cleanup=None):
  1832. """
  1833. Transfers the Geometry or Excellon from it's editor to the current object.
  1834. :return: None
  1835. """
  1836. self.defaults.report_usage("editor2object()")
  1837. # re-enable the objects menu that was disabled on entry in Editor mode
  1838. self.ui.menuobjects.setDisabled(False)
  1839. # do not update a geometry or excellon object unless it comes out of an editor
  1840. if self.call_source != 'app':
  1841. edited_obj = self.collection.get_active()
  1842. if cleanup is None:
  1843. msgbox = QtWidgets.QMessageBox()
  1844. msgbox.setText(_("Do you want to save the edited object?"))
  1845. msgbox.setWindowTitle(_("Close Editor"))
  1846. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1847. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1848. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1849. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1850. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1851. msgbox.setDefaultButton(bt_yes)
  1852. msgbox.exec_()
  1853. response = msgbox.clickedButton()
  1854. if response == bt_yes:
  1855. # show the Tools Toolbar
  1856. tools_tb = self.ui.toolbartools
  1857. tools_tb.show()
  1858. # clean the Tools Tab
  1859. self.ui.tool_scroll_area.takeWidget()
  1860. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1861. self.ui.notebook.setTabText(2, "Tool")
  1862. if isinstance(edited_obj, GeometryObject):
  1863. obj_type = "Geometry"
  1864. self.geo_editor.update_fcgeometry(edited_obj)
  1865. # self.geo_editor.update_options(edited_obj)
  1866. # restore GUI to the Selected TAB
  1867. # Remove anything else in the appGUI
  1868. self.ui.tool_scroll_area.takeWidget()
  1869. # update the geo object options so it is including the bounding box values
  1870. try:
  1871. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1872. edited_obj.options['xmin'] = xmin
  1873. edited_obj.options['ymin'] = ymin
  1874. edited_obj.options['xmax'] = xmax
  1875. edited_obj.options['ymax'] = ymax
  1876. except AttributeError as e:
  1877. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1878. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1879. edited_obj.build_ui()
  1880. edited_obj.plot()
  1881. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1882. elif isinstance(edited_obj, GerberObject):
  1883. obj_type = "Gerber"
  1884. self.grb_editor.update_fcgerber()
  1885. # self.grb_editor.update_options(edited_obj)
  1886. # delete the old object (the source object) if it was an empty one
  1887. try:
  1888. if len(edited_obj.solid_geometry) == 0:
  1889. old_name = edited_obj.options['name']
  1890. self.collection.delete_by_name(old_name)
  1891. except TypeError:
  1892. # if the solid_geometry is a single Polygon the len() will not work
  1893. # in any case, falling here means that we have something in the solid_geometry, even if only
  1894. # a single Polygon, therefore we pass this
  1895. pass
  1896. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1897. # restore GUI to the Selected TAB
  1898. # Remove anything else in the GUI
  1899. self.ui.selected_scroll_area.takeWidget()
  1900. elif isinstance(edited_obj, ExcellonObject):
  1901. obj_type = "Excellon"
  1902. self.exc_editor.update_fcexcellon(edited_obj)
  1903. # self.exc_editor.update_options(edited_obj)
  1904. # restore GUI to the Selected TAB
  1905. # Remove anything else in the GUI
  1906. self.ui.tool_scroll_area.takeWidget()
  1907. # delete the old object (the source object) if it was an empty one
  1908. # find if we have drills:
  1909. has_drills = None
  1910. for tt in edited_obj.tools:
  1911. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1912. has_drills = True
  1913. break
  1914. # find if we have slots:
  1915. has_slots = None
  1916. for tt in edited_obj.tools:
  1917. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1918. has_slots = True
  1919. break
  1920. if has_drills is None and has_slots is None:
  1921. old_name = edited_obj.options['name']
  1922. self.collection.delete_by_name(name=old_name)
  1923. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1924. else:
  1925. self.inform.emit('[WARNING_NOTCL] %s' %
  1926. _("Select a Gerber, Geometry or Excellon Object to update."))
  1927. return
  1928. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1929. elif response == bt_no:
  1930. # show the Tools Toolbar
  1931. tools_tb = self.ui.toolbartools
  1932. tools_tb.show()
  1933. # clean the Tools Tab
  1934. self.ui.tool_scroll_area.takeWidget()
  1935. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1936. self.ui.notebook.setTabText(2, "Tool")
  1937. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1938. if isinstance(edited_obj, GeometryObject):
  1939. self.geo_editor.deactivate()
  1940. edited_obj.build_ui()
  1941. edited_obj.plot()
  1942. elif isinstance(edited_obj, GerberObject):
  1943. self.grb_editor.deactivate_grb_editor()
  1944. edited_obj.build_ui()
  1945. elif isinstance(edited_obj, ExcellonObject):
  1946. self.exc_editor.deactivate()
  1947. edited_obj.build_ui()
  1948. else:
  1949. self.inform.emit('[WARNING_NOTCL] %s' %
  1950. _("Select a Gerber, Geometry or Excellon Object to update."))
  1951. return
  1952. elif response == bt_cancel:
  1953. return
  1954. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1955. # edited_obj.build_ui()
  1956. # Switch notebook to Selected page
  1957. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1958. else:
  1959. # show the Tools Toolbar
  1960. tools_tb = self.ui.toolbartools
  1961. tools_tb.show()
  1962. if isinstance(edited_obj, GeometryObject):
  1963. self.geo_editor.deactivate()
  1964. elif isinstance(edited_obj, GerberObject):
  1965. self.grb_editor.deactivate_grb_editor()
  1966. elif isinstance(edited_obj, ExcellonObject):
  1967. self.exc_editor.deactivate()
  1968. else:
  1969. self.inform.emit('[WARNING_NOTCL] %s' %
  1970. _("Select a Gerber, Geometry or Excellon Object to update."))
  1971. return
  1972. # if notebook is hidden we show it
  1973. if self.ui.splitter.sizes()[0] == 0:
  1974. self.ui.splitter.setSizes([1, 1])
  1975. # restore the call_source to app
  1976. self.call_source = 'app'
  1977. # edited_obj.plot()
  1978. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1979. self.ui.plot_tab_area.protectTab(0)
  1980. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1981. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1982. self.ui.project_frame.setDisabled(False)
  1983. def get_last_folder(self):
  1984. """
  1985. Get the folder path from where the last file was opened.
  1986. :return: String, last opened folder path
  1987. """
  1988. return self.defaults["global_last_folder"]
  1989. def get_last_save_folder(self):
  1990. """
  1991. Get the folder path from where the last file was saved.
  1992. :return: String, last saved folder path
  1993. """
  1994. loc = self.defaults["global_last_save_folder"]
  1995. if loc is None:
  1996. loc = self.defaults["global_last_folder"]
  1997. if loc is None:
  1998. loc = os.path.dirname(__file__)
  1999. return loc
  2000. @QtCore.pyqtSlot(str)
  2001. @QtCore.pyqtSlot(str, bool)
  2002. def info(self, msg, shell_echo=True):
  2003. """
  2004. Informs the user. Normally on the status bar, optionally
  2005. also on the shell.
  2006. :param msg: Text to write.
  2007. :type msg: str
  2008. :param shell_echo: Control if to display the message msg in the Shell
  2009. :type shell_echo: bool
  2010. :return: None
  2011. """
  2012. # Type of message in brackets at the beginning of the message.
  2013. match = re.search(r"\[(.*)\](.*)", msg)
  2014. if match:
  2015. level = match.group(1)
  2016. msg_ = match.group(2)
  2017. self.ui.fcinfo.set_status(str(msg_), level=level)
  2018. if shell_echo is True:
  2019. if level.lower() == "error":
  2020. self.shell_message(msg, error=True, show=True)
  2021. elif level.lower() == "warning":
  2022. self.shell_message(msg, warning=True, show=True)
  2023. elif level.lower() == "error_notcl":
  2024. self.shell_message(msg, error=True, show=False)
  2025. elif level.lower() == "warning_notcl":
  2026. self.shell_message(msg, warning=True, show=False)
  2027. elif level.lower() == "success":
  2028. self.shell_message(msg, success=True, show=False)
  2029. elif level.lower() == "selected":
  2030. self.shell_message(msg, selected=True, show=False)
  2031. else:
  2032. self.shell_message(msg, show=False)
  2033. else:
  2034. self.ui.fcinfo.set_status(str(msg), level="info")
  2035. # make sure that if the message is to clear the infobar with a space
  2036. # is not printed over and over on the shell
  2037. if msg != '' and shell_echo is True:
  2038. self.shell_message(msg)
  2039. def info_shell(self, msg):
  2040. self.shell_message(msg=msg)
  2041. def on_import_preferences(self):
  2042. """
  2043. Loads the application default settings from a saved file into
  2044. ``self.defaults`` dictionary.
  2045. :return: None
  2046. """
  2047. self.defaults.report_usage("on_import_preferences")
  2048. App.log.debug("App.on_import_preferences()")
  2049. # Show file chooser
  2050. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2051. try:
  2052. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2053. directory=self.data_path,
  2054. filter=filter_)
  2055. except TypeError:
  2056. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2057. filter=filter_)
  2058. filename = str(filename)
  2059. if filename == "":
  2060. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2061. return
  2062. # Load in the defaults from the chosen file
  2063. self.defaults.load(filename=filename)
  2064. self.preferencesUiManager.on_preferences_edited()
  2065. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2066. def on_export_preferences(self):
  2067. """
  2068. Save the defaults dictionary to a file.
  2069. :return: None
  2070. """
  2071. self.defaults.report_usage("on_export_preferences")
  2072. App.log.debug("on_export_preferences()")
  2073. # defaults_file_content = None
  2074. # Show file chooser
  2075. date = str(datetime.today()).rpartition('.')[0]
  2076. date = ''.join(c for c in date if c not in ':-')
  2077. date = date.replace(' ', '_')
  2078. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2079. try:
  2080. filename, _f = FCFileSaveDialog.get_saved_filename(
  2081. caption=_("Export FlatCAM Preferences"),
  2082. directory=self.data_path + '/preferences_' + date,
  2083. ext_filter=filter__
  2084. )
  2085. except TypeError:
  2086. filename, _f = FCFileSaveDialog.get_saved_filename(
  2087. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2088. filename = str(filename)
  2089. if filename == "":
  2090. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2091. return
  2092. # Update options
  2093. self.preferencesUiManager.defaults_read_form()
  2094. self.defaults.propagate_defaults()
  2095. # Save update options
  2096. try:
  2097. self.defaults.write(filename=filename)
  2098. except Exception:
  2099. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2100. return
  2101. if self.defaults["global_open_style"] is False:
  2102. self.file_opened.emit("preferences", filename)
  2103. self.file_saved.emit("preferences", filename)
  2104. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2105. def save_to_file(self, content_to_save, txt_content):
  2106. """
  2107. Save something to a file.
  2108. :return: None
  2109. """
  2110. self.defaults.report_usage("save_to_file")
  2111. App.log.debug("save_to_file()")
  2112. self.date = str(datetime.today()).rpartition('.')[0]
  2113. self.date = ''.join(c for c in self.date if c not in ':-')
  2114. self.date = self.date.replace(' ', '_')
  2115. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2116. path_to_save = self.defaults["global_last_save_folder"] if \
  2117. self.defaults["global_last_save_folder"] is not None else self.data_path
  2118. try:
  2119. filename, _f = FCFileSaveDialog.get_saved_filename(
  2120. caption=_("Save to file"),
  2121. directory=path_to_save + '/file_' + self.date,
  2122. ext_filter=filter__
  2123. )
  2124. except TypeError:
  2125. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2126. filename = str(filename)
  2127. if filename == "":
  2128. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2129. return
  2130. else:
  2131. try:
  2132. with open(filename, 'w') as f:
  2133. ___ = f.read()
  2134. except PermissionError:
  2135. self.inform.emit('[WARNING] %s' %
  2136. _("Permission denied, saving not possible.\n"
  2137. "Most likely another app is holding the file open and not accessible."))
  2138. return
  2139. except IOError:
  2140. App.log.debug('Creating a new file ...')
  2141. f = open(filename, 'w')
  2142. f.close()
  2143. except Exception:
  2144. e = sys.exc_info()[0]
  2145. App.log.error("Could not load the file.")
  2146. App.log.error(str(e))
  2147. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2148. return
  2149. # Save content
  2150. if filename.rpartition('.')[2].lower() == 'html':
  2151. file_content = content_to_save
  2152. else:
  2153. file_content = txt_content
  2154. try:
  2155. with open(filename, "w") as f:
  2156. f.write(file_content)
  2157. except Exception:
  2158. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2159. return
  2160. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2161. def register_recent(self, kind, filename):
  2162. """
  2163. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2164. dictionary.
  2165. :param kind: type of file that was opened
  2166. :param filename: the path and file name for the file that was opened
  2167. :return:
  2168. """
  2169. self.log.debug("register_recent()")
  2170. self.log.debug(" %s" % kind)
  2171. self.log.debug(" %s" % filename)
  2172. record = {'kind': str(kind), 'filename': str(filename)}
  2173. if record in self.recent:
  2174. return
  2175. if record in self.recent_projects:
  2176. return
  2177. if record['kind'] == 'project':
  2178. self.recent_projects.insert(0, record)
  2179. else:
  2180. self.recent.insert(0, record)
  2181. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2182. self.recent.pop()
  2183. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2184. self.recent_projects.pop()
  2185. try:
  2186. f = open(self.data_path + '/recent.json', 'w')
  2187. except IOError:
  2188. App.log.error("Failed to open recent items file for writing.")
  2189. self.inform.emit('[ERROR_NOTCL] %s' %
  2190. _('Failed to open recent files file for writing.'))
  2191. return
  2192. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2193. f.close()
  2194. try:
  2195. fp = open(self.data_path + '/recent_projects.json', 'w')
  2196. except IOError:
  2197. App.log.error("Failed to open recent items file for writing.")
  2198. self.inform.emit('[ERROR_NOTCL] %s' %
  2199. _('Failed to open recent projects file for writing.'))
  2200. return
  2201. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2202. fp.close()
  2203. # Re-build the recent items menu
  2204. self.setup_recent_items()
  2205. def on_about(self):
  2206. """
  2207. Displays the "about" dialog found in the Menu --> Help.
  2208. :return: None
  2209. """
  2210. self.defaults.report_usage("on_about")
  2211. version = self.version
  2212. version_date = self.version_date
  2213. beta = self.beta
  2214. class AboutDialog(QtWidgets.QDialog):
  2215. def __init__(self, app, parent=None):
  2216. QtWidgets.QDialog.__init__(self, parent)
  2217. self.app = app
  2218. # Icon and title
  2219. self.setWindowIcon(parent.app_icon)
  2220. self.setWindowTitle(_("About FlatCAM"))
  2221. self.resize(600, 200)
  2222. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2223. # self.setStyleSheet(
  2224. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2225. # "background-attachment: fixed"
  2226. # )
  2227. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2228. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2229. # palette = QtGui.QPalette()
  2230. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2231. # self.setPalette(palette)
  2232. logo = QtWidgets.QLabel()
  2233. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2234. title = QtWidgets.QLabel(
  2235. "<font size=8><B>FlatCAM</B></font><BR>"
  2236. "{title}<BR>"
  2237. "<BR>"
  2238. "<BR>"
  2239. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2240. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2241. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2242. "<B>{issue}</B></a><BR>".format(
  2243. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2244. devel=_("Development"),
  2245. down=_("DOWNLOAD"),
  2246. issue=_("Issue tracker"))
  2247. )
  2248. title.setOpenExternalLinks(True)
  2249. closebtn = QtWidgets.QPushButton(_("Close"))
  2250. tab_widget = QtWidgets.QTabWidget()
  2251. description_label = QtWidgets.QLabel(
  2252. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2253. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2254. version=version,
  2255. beta=('BETA' if beta else ''),
  2256. date=version_date,
  2257. arch=platform.architecture()[0])
  2258. )
  2259. description_label.setOpenExternalLinks(True)
  2260. lic_lbl_header = QtWidgets.QLabel(
  2261. '%s:<br>%s<br>' % (
  2262. _('Licensed under the MIT license'),
  2263. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2264. "http://www.opensource.org/licenses/mit-license.php</a>"
  2265. )
  2266. )
  2267. lic_lbl_header.setOpenExternalLinks(True)
  2268. lic_lbl_body = QtWidgets.QLabel(
  2269. _(
  2270. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2271. 'of this software and associated documentation files (the "Software"), to deal\n'
  2272. 'in the Software without restriction, including without limitation the rights\n'
  2273. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2274. 'copies of the Software, and to permit persons to whom the Software is\n'
  2275. 'furnished to do so, subject to the following conditions:\n\n'
  2276. 'The above copyright notice and this permission notice shall be included in\n'
  2277. 'all copies or substantial portions of the Software.\n\n'
  2278. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2279. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2280. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2281. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2282. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2283. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2284. 'THE SOFTWARE.'
  2285. )
  2286. )
  2287. attributions_label = QtWidgets.QLabel(
  2288. _(
  2289. 'Some of the icons used are from the following sources:<br>'
  2290. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2291. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2292. 'title="Flaticon">www.flaticon.com</a></div>'
  2293. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2294. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2295. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2296. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2297. 'title="Flaticon">www.flaticon.com</a></div>'
  2298. )
  2299. )
  2300. attributions_label.setOpenExternalLinks(True)
  2301. # layouts
  2302. layout1 = QtWidgets.QVBoxLayout()
  2303. layout1_1 = QtWidgets.QHBoxLayout()
  2304. layout1_2 = QtWidgets.QHBoxLayout()
  2305. layout2 = QtWidgets.QHBoxLayout()
  2306. layout3 = QtWidgets.QHBoxLayout()
  2307. self.setLayout(layout1)
  2308. layout1.addLayout(layout1_1)
  2309. layout1.addLayout(layout1_2)
  2310. layout1.addLayout(layout2)
  2311. layout1.addLayout(layout3)
  2312. layout1_1.addStretch()
  2313. layout1_1.addWidget(description_label)
  2314. layout1_2.addWidget(tab_widget)
  2315. self.splash_tab = QtWidgets.QWidget()
  2316. self.splash_tab.setObjectName("splash_about")
  2317. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2318. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2319. tab_widget.addTab(self.splash_tab, _("Splash"))
  2320. self.programmmers_tab = QtWidgets.QWidget()
  2321. self.programmmers_tab.setObjectName("programmers_about")
  2322. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2323. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2324. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2325. self.translators_tab = QtWidgets.QWidget()
  2326. self.translators_tab.setObjectName("translators_about")
  2327. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2328. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2329. tab_widget.addTab(self.translators_tab, _("Translators"))
  2330. self.license_tab = QtWidgets.QWidget()
  2331. self.license_tab.setObjectName("license_about")
  2332. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2333. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2334. tab_widget.addTab(self.license_tab, _("License"))
  2335. self.attributions_tab = QtWidgets.QWidget()
  2336. self.attributions_tab.setObjectName("attributions_about")
  2337. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2338. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2339. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2340. self.splash_tab_layout.addWidget(logo, stretch=0)
  2341. self.splash_tab_layout.addWidget(title, stretch=1)
  2342. pal = QtGui.QPalette()
  2343. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2344. self.prog_grid_lay = QtWidgets.QGridLayout()
  2345. self.prog_grid_lay.setHorizontalSpacing(20)
  2346. self.prog_grid_lay.setColumnStretch(0, 0)
  2347. self.prog_grid_lay.setColumnStretch(2, 1)
  2348. prog_widget = QtWidgets.QWidget()
  2349. prog_widget.setLayout(self.prog_grid_lay)
  2350. prog_scroll = QtWidgets.QScrollArea()
  2351. prog_scroll.setWidget(prog_widget)
  2352. prog_scroll.setWidgetResizable(True)
  2353. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2354. prog_scroll.setPalette(pal)
  2355. self.programmmers_tab_layout.addWidget(prog_scroll)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2402. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2403. self.translator_grid_lay = QtWidgets.QGridLayout()
  2404. self.translator_grid_lay.setColumnStretch(0, 0)
  2405. self.translator_grid_lay.setColumnStretch(1, 0)
  2406. self.translator_grid_lay.setColumnStretch(2, 1)
  2407. self.translator_grid_lay.setColumnStretch(3, 0)
  2408. # trans_widget = QtWidgets.QWidget()
  2409. # trans_widget.setLayout(self.translator_grid_lay)
  2410. # self.translators_tab_layout.addWidget(trans_widget)
  2411. # self.translators_tab_layout.addStretch()
  2412. trans_widget = QtWidgets.QWidget()
  2413. trans_widget.setLayout(self.translator_grid_lay)
  2414. trans_scroll = QtWidgets.QScrollArea()
  2415. trans_scroll.setWidget(trans_widget)
  2416. trans_scroll.setWidgetResizable(True)
  2417. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2418. trans_scroll.setPalette(pal)
  2419. self.translators_tab_layout.addWidget(trans_scroll)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2430. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2449. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2450. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2451. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2452. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2453. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2454. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2455. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2456. self.translator_grid_lay.setColumnStretch(0, 0)
  2457. self.translators_tab_layout.addStretch()
  2458. self.license_tab_layout.addWidget(lic_lbl_header)
  2459. self.license_tab_layout.addWidget(lic_lbl_body)
  2460. self.license_tab_layout.addStretch()
  2461. self.attributions_tab_layout.addWidget(attributions_label)
  2462. self.attributions_tab_layout.addStretch()
  2463. layout3.addStretch()
  2464. layout3.addWidget(closebtn)
  2465. closebtn.clicked.connect(self.accept)
  2466. AboutDialog(app=self, parent=self.ui).exec_()
  2467. def on_readme(self):
  2468. """
  2469. Displays the "about" dialog found in the Menu --> Help.
  2470. :return: None
  2471. """
  2472. class ReadmeDialog(QtWidgets.QDialog):
  2473. def __init__(self, app, parent=None):
  2474. QtWidgets.QDialog.__init__(self, parent)
  2475. self.app = app
  2476. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2477. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2478. "<b>click</b></a>"
  2479. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2480. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2481. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2482. # Icon and title
  2483. self.setWindowIcon(parent.app_icon)
  2484. self.setWindowTitle(_("Important Information's"))
  2485. self.resize(750, 375)
  2486. logo = QtWidgets.QLabel()
  2487. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2488. # content = QtWidgets.QLabel(
  2489. # "%s<br>"
  2490. # "%s<br><br>"
  2491. # "%s,<br>"
  2492. # "%s<br>"
  2493. # "<ul>"
  2494. # "<li> &nbsp;%s %s</li>"
  2495. # "<li> &nbsp;%s %s</li>"
  2496. # "</ul>"
  2497. # "%s %s.<br>"
  2498. # "%s"
  2499. # "<ul>"
  2500. # "<li> &nbsp;%s &#128077;</li>"
  2501. # "<li> &nbsp;%s &#128513;</li>"
  2502. # "</ul>" %
  2503. # (
  2504. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2505. # _("Yet it cannot evolve without <b>contributions</b>."),
  2506. # _("If you want to see this application grow and become better and better"),
  2507. # _("you can <b>contribute</b> to the development yourself by:"),
  2508. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2509. # new_features_link,
  2510. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2511. # bugs_link,
  2512. # _("If you like or use this program you can make a donation"),
  2513. # donation_link,
  2514. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2515. # _("it will be welcomed with joy"),
  2516. # _("it will give me a reason to continue")
  2517. # )
  2518. # )
  2519. content = QtWidgets.QLabel(
  2520. "%s<br>"
  2521. "%s<br><br>"
  2522. "%s,<br>"
  2523. "%s<br>"
  2524. "<ul>"
  2525. "<li> &nbsp;%s %s</li>"
  2526. "<li> &nbsp;%s %s</li>"
  2527. "</ul>" %
  2528. (
  2529. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2530. _("Yet it cannot evolve without <b>contributions</b>."),
  2531. _("If you want to see this application grow and become better and better"),
  2532. _("you can <b>contribute</b> to the development yourself by:"),
  2533. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2534. new_features_link,
  2535. _("Bug Reports by providing the steps required to reproduce the bug"),
  2536. bugs_link
  2537. )
  2538. )
  2539. content.setOpenExternalLinks(True)
  2540. # palette
  2541. pal = QtGui.QPalette()
  2542. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2543. # layouts
  2544. main_layout = QtWidgets.QVBoxLayout()
  2545. self.setLayout(main_layout)
  2546. tab_layout = QtWidgets.QHBoxLayout()
  2547. buttons_hlay = QtWidgets.QHBoxLayout()
  2548. main_layout.addLayout(tab_layout)
  2549. main_layout.addLayout(buttons_hlay)
  2550. tab_widget = QtWidgets.QTabWidget()
  2551. tab_layout.addWidget(tab_widget)
  2552. closebtn = QtWidgets.QPushButton(_("Close"))
  2553. buttons_hlay.addStretch()
  2554. buttons_hlay.addWidget(closebtn)
  2555. # CONTRIBUTE section
  2556. self.intro_tab = QtWidgets.QWidget()
  2557. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2558. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2559. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2560. self.grid_lay = QtWidgets.QGridLayout()
  2561. self.grid_lay.setHorizontalSpacing(20)
  2562. self.grid_lay.setColumnStretch(0, 0)
  2563. self.grid_lay.setColumnStretch(1, 1)
  2564. intro_wdg = QtWidgets.QWidget()
  2565. intro_wdg.setLayout(self.grid_lay)
  2566. intro_scroll_area = QtWidgets.QScrollArea()
  2567. intro_scroll_area.setWidget(intro_wdg)
  2568. intro_scroll_area.setWidgetResizable(True)
  2569. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2570. intro_scroll_area.setPalette(pal)
  2571. self.grid_lay.addWidget(logo, 0, 0)
  2572. self.grid_lay.addWidget(content, 0, 1)
  2573. self.intro_tab_layout.addWidget(intro_scroll_area)
  2574. # LINKS EXCHANGE section
  2575. self.links_tab = QtWidgets.QWidget()
  2576. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2577. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2578. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2579. self.links_lay = QtWidgets.QHBoxLayout()
  2580. links_wdg = QtWidgets.QWidget()
  2581. links_wdg.setLayout(self.links_lay)
  2582. links_scroll_area = QtWidgets.QScrollArea()
  2583. links_scroll_area.setWidget(links_wdg)
  2584. links_scroll_area.setWidgetResizable(True)
  2585. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2586. links_scroll_area.setPalette(pal)
  2587. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2588. self.links_tab_layout.addWidget(links_scroll_area)
  2589. # HOW TO section
  2590. self.howto_tab = QtWidgets.QWidget()
  2591. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2592. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2593. tab_widget.addTab(self.howto_tab, _("How To's"))
  2594. self.howto_lay = QtWidgets.QHBoxLayout()
  2595. howto_wdg = QtWidgets.QWidget()
  2596. howto_wdg.setLayout(self.howto_lay)
  2597. howto_scroll_area = QtWidgets.QScrollArea()
  2598. howto_scroll_area.setWidget(howto_wdg)
  2599. howto_scroll_area.setWidgetResizable(True)
  2600. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2601. howto_scroll_area.setPalette(pal)
  2602. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2603. self.howto_tab_layout.addWidget(howto_scroll_area)
  2604. # BUTTONS section
  2605. closebtn.clicked.connect(self.accept)
  2606. ReadmeDialog(app=self, parent=self.ui).exec_()
  2607. def install_bookmarks(self, book_dict=None):
  2608. """
  2609. Install the bookmarks actions in the Help menu -> Bookmarks
  2610. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2611. :return: None
  2612. """
  2613. if book_dict is None:
  2614. self.defaults["global_bookmarks"].update(
  2615. {
  2616. '1': ['FlatCAM', "http://flatcam.org"],
  2617. '2': ['Backup Site', ""]
  2618. }
  2619. )
  2620. else:
  2621. self.defaults["global_bookmarks"].clear()
  2622. self.defaults["global_bookmarks"].update(book_dict)
  2623. # first try to disconnect if somehow they get connected from elsewhere
  2624. for act in self.ui.menuhelp_bookmarks.actions():
  2625. try:
  2626. act.triggered.disconnect()
  2627. except TypeError:
  2628. pass
  2629. # clear all actions except the last one who is the Bookmark manager
  2630. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2631. pass
  2632. else:
  2633. self.ui.menuhelp_bookmarks.removeAction(act)
  2634. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2635. if self.defaults["global_bookmarks"]:
  2636. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2637. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2638. # the JSON is first making the keys as strings (therefore I have to use strings too
  2639. # or do the conversion :(
  2640. # )
  2641. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2642. # the '10' entry jsut after '1' therefore ordering as strings
  2643. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2644. key=lambda x: int(x[0]))
  2645. for entry, bookmark in sorted_bookmarks:
  2646. title = bookmark[0]
  2647. weblink = bookmark[1]
  2648. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2649. act.setText(title)
  2650. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2651. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2652. if title == 'Backup Site' and weblink == "":
  2653. act.triggered.connect(self.on_backup_site)
  2654. else:
  2655. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2656. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2657. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2658. def on_bookmarks_manager(self):
  2659. """
  2660. Adds the bookmark manager in a Tab in Plot Area
  2661. :return:
  2662. """
  2663. for idx in range(self.ui.plot_tab_area.count()):
  2664. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2665. # there can be only one instance of Bookmark Manager at one time
  2666. return
  2667. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2668. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2669. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2670. # add the tab if it was closed
  2671. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2672. # delete the absolute and relative position and messages in the infobar
  2673. # self.ui.position_label.setText("")
  2674. # self.ui.rel_position_label.setText("")
  2675. # hide coordinates toolbars in the infobar while in DB
  2676. self.ui.coords_toolbar.hide()
  2677. self.ui.delta_coords_toolbar.hide()
  2678. # Switch plot_area to preferences page
  2679. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2680. def on_backup_site(self):
  2681. msgbox = QtWidgets.QMessageBox()
  2682. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2683. "1. FlatCAM.org website is down\n"
  2684. "2. Someone forked FlatCAM project and wants to point\n"
  2685. "to his own website\n\n"
  2686. "If you can't get any informations about FlatCAM beta\n"
  2687. "use the YouTube channel link from the Help menu."))
  2688. msgbox.setWindowTitle(_("Alternative website"))
  2689. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2690. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2691. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2692. msgbox.setDefaultButton(bt_yes)
  2693. msgbox.exec_()
  2694. # response = msgbox.clickedButton()
  2695. def on_file_savedefaults(self):
  2696. """
  2697. Callback for menu item File->Save Defaults. Saves application default options
  2698. ``self.defaults`` to current_defaults.FlatConfig.
  2699. :return: None
  2700. """
  2701. self.preferencesUiManager.save_defaults()
  2702. def final_save(self):
  2703. """
  2704. Callback for doing a preferences save to file whenever the application is about to quit.
  2705. If the project has changes, it will ask the user to save the project.
  2706. :return: None
  2707. """
  2708. if self.save_in_progress:
  2709. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2710. return
  2711. if self.should_we_save and self.collection.get_list():
  2712. msgbox = QtWidgets.QMessageBox()
  2713. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2714. "\n"
  2715. "Do you want to Save the project?"))
  2716. msgbox.setWindowTitle(_("Save changes"))
  2717. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2718. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2719. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2720. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2721. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2722. msgbox.setDefaultButton(bt_yes)
  2723. msgbox.exec_()
  2724. response = msgbox.clickedButton()
  2725. if response == bt_yes:
  2726. try:
  2727. self.trayIcon.hide()
  2728. except Exception:
  2729. pass
  2730. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2731. elif response == bt_no:
  2732. try:
  2733. self.trayIcon.hide()
  2734. except Exception:
  2735. pass
  2736. self.quit_application()
  2737. elif response == bt_cancel:
  2738. return
  2739. else:
  2740. try:
  2741. self.trayIcon.hide()
  2742. except Exception:
  2743. pass
  2744. self.quit_application()
  2745. def quit_application(self):
  2746. """
  2747. Called (as a pyslot or not) when the application is quit.
  2748. :return: None
  2749. """
  2750. # close editors before quiting the app, if they are open
  2751. if self.geo_editor.editor_active is True:
  2752. self.geo_editor.deactivate()
  2753. try:
  2754. self.geo_editor.disconnect()
  2755. except TypeError:
  2756. pass
  2757. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2758. if self.exc_editor.editor_active is True:
  2759. self.exc_editor.deactivate()
  2760. try:
  2761. self.grb_editor.disconnect()
  2762. except TypeError:
  2763. pass
  2764. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2765. if self.grb_editor.editor_active is True:
  2766. self.grb_editor.deactivate_grb_editor()
  2767. try:
  2768. self.exc_editor.disconnect()
  2769. except TypeError:
  2770. pass
  2771. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2772. # disconnect the mouse events
  2773. if self.is_legacy:
  2774. self.plotcanvas.graph_event_disconnect(self.mm)
  2775. self.plotcanvas.graph_event_disconnect(self.mp)
  2776. self.plotcanvas.graph_event_disconnect(self.mr)
  2777. self.plotcanvas.graph_event_disconnect(self.mdc)
  2778. self.plotcanvas.graph_event_disconnect(self.kp)
  2779. else:
  2780. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2781. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2782. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2783. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2784. self.on_mouse_double_click_over_plot)
  2785. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2786. self.preferencesUiManager.save_defaults(silent=True)
  2787. log.debug("App.quit_application() --> App Defaults saved.")
  2788. if self.cmd_line_headless != 1:
  2789. # save app state to file
  2790. stgs = QSettings("Open Source", "FlatCAM")
  2791. stgs.setValue('saved_gui_state', self.ui.saveState())
  2792. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2793. stgs.setValue(
  2794. 'language',
  2795. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2796. )
  2797. stgs.setValue(
  2798. 'notebook_font_size',
  2799. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2800. )
  2801. stgs.setValue(
  2802. 'axis_font_size',
  2803. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2804. )
  2805. stgs.setValue(
  2806. 'textbox_font_size',
  2807. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2808. )
  2809. stgs.setValue(
  2810. 'hud_font_size',
  2811. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2812. )
  2813. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2814. stgs.setValue(
  2815. 'machinist',
  2816. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2817. )
  2818. # This will write the setting to the platform specific storage.
  2819. del stgs
  2820. log.debug("App.quit_application() --> App UI state saved.")
  2821. # try to quit the Socket opened by ArgsThread class
  2822. try:
  2823. # self.new_launch.thread_exit = True
  2824. # self.new_launch.listener.close()
  2825. self.new_launch.stop.emit()
  2826. except Exception as err:
  2827. log.debug("App.quit_application() --> %s" % str(err))
  2828. # try to quit the QThread that run ArgsThread class
  2829. try:
  2830. # del self.new_launch
  2831. self.listen_th.quit()
  2832. except Exception as e:
  2833. log.debug("App.quit_application() --> %s" % str(e))
  2834. # terminate workers
  2835. # self.workers.__del__()
  2836. self.clear_pool()
  2837. # quit app by signalling for self.kill_app() method
  2838. # self.close_app_signal.emit()
  2839. QtWidgets.qApp.quit()
  2840. sys.exit(0)
  2841. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2842. # we use the following command
  2843. # minor_v = sys.version_info.minor
  2844. # if minor_v < 8:
  2845. # # make sure that the app closes
  2846. # sys.exit(0)
  2847. # else:
  2848. # os._exit(0) # fix to work with Python 3.8
  2849. @staticmethod
  2850. def kill_app():
  2851. QtWidgets.qApp.quit()
  2852. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2853. # we use the following command
  2854. sys.exit(0)
  2855. def on_portable_checked(self, state):
  2856. """
  2857. Callback called when the checkbox in Preferences GUI is checked.
  2858. It will set the application as portable by creating the preferences and recent files in the
  2859. 'config' folder found in the FlatCAM installation folder.
  2860. :param state: boolean, the state of the checkbox when clicked/checked
  2861. :return:
  2862. """
  2863. line_no = 0
  2864. data = None
  2865. if sys.platform != 'win32':
  2866. # this won't work in Linux or MacOS
  2867. return
  2868. # test if the app was frozen and choose the path for the configuration file
  2869. if getattr(sys, "frozen", False) is True:
  2870. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2871. else:
  2872. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2873. config_file = current_data_path + '\\configuration.txt'
  2874. try:
  2875. with open(config_file, 'r') as f:
  2876. try:
  2877. data = f.readlines()
  2878. except Exception as e:
  2879. log.debug('App.__init__() -->%s' % str(e))
  2880. return
  2881. except FileNotFoundError:
  2882. pass
  2883. for line in data:
  2884. line = line.strip('\n')
  2885. param = str(line).rpartition('=')
  2886. if param[0] == 'portable':
  2887. break
  2888. line_no += 1
  2889. if state:
  2890. data[line_no] = 'portable=True\n'
  2891. # create the new defauults files
  2892. # create current_defaults.FlatConfig file if there is none
  2893. try:
  2894. f = open(current_data_path + '/current_defaults.FlatConfig')
  2895. f.close()
  2896. except IOError:
  2897. App.log.debug('Creating empty current_defaults.FlatConfig')
  2898. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2899. json.dump({}, f)
  2900. f.close()
  2901. # create factory_defaults.FlatConfig file if there is none
  2902. try:
  2903. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2904. f.close()
  2905. except IOError:
  2906. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2907. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2908. json.dump({}, f)
  2909. f.close()
  2910. try:
  2911. f = open(current_data_path + '/recent.json')
  2912. f.close()
  2913. except IOError:
  2914. App.log.debug('Creating empty recent.json')
  2915. f = open(current_data_path + '/recent.json', 'w')
  2916. json.dump([], f)
  2917. f.close()
  2918. try:
  2919. fp = open(current_data_path + '/recent_projects.json')
  2920. fp.close()
  2921. except IOError:
  2922. App.log.debug('Creating empty recent_projects.json')
  2923. fp = open(current_data_path + '/recent_projects.json', 'w')
  2924. json.dump([], fp)
  2925. fp.close()
  2926. # save the current defaults to the new defaults file
  2927. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2928. else:
  2929. data[line_no] = 'portable=False\n'
  2930. with open(config_file, 'w') as f:
  2931. f.writelines(data)
  2932. def on_register_files(self, obj_type=None):
  2933. """
  2934. Called whenever there is a need to register file extensions with FlatCAM.
  2935. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2936. :param obj_type: the type of object to be register for.
  2937. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2938. :return: None
  2939. """
  2940. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2941. new_reg_path = 'Software\\Classes\\'
  2942. # find if the current user is admin
  2943. try:
  2944. is_admin = os.getuid() == 0
  2945. except AttributeError:
  2946. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2947. if is_admin is True:
  2948. root_path = winreg.HKEY_LOCAL_MACHINE
  2949. else:
  2950. root_path = winreg.HKEY_CURRENT_USER
  2951. # create the keys
  2952. def set_reg(name, root_pth, new_reg_path, value):
  2953. try:
  2954. winreg.CreateKey(root_pth, new_reg_path)
  2955. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2956. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2957. return True
  2958. except WindowsError:
  2959. return False
  2960. # delete key in registry
  2961. def delete_reg(root_pth, reg_path, key_to_del):
  2962. key_to_del_path = reg_path + key_to_del
  2963. try:
  2964. winreg.DeleteKey(root_pth, key_to_del_path)
  2965. return True
  2966. except WindowsError:
  2967. return False
  2968. if obj_type is None or obj_type == 'excellon':
  2969. exc_list = \
  2970. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2971. exc_list = [x for x in exc_list if x != '']
  2972. # register all keys in the Preferences window
  2973. for ext in exc_list:
  2974. new_k = new_reg_path + '.%s' % ext
  2975. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2976. # and unregister those that are no longer in the Preferences windows but are in the file
  2977. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2978. if ext not in exc_list:
  2979. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2980. # now write the updated extensions to the self.defaults
  2981. # new_ext = ''
  2982. # for ext in exc_list:
  2983. # new_ext = new_ext + ext + ', '
  2984. # self.defaults["fa_excellon"] = new_ext
  2985. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2986. if obj_type is None or obj_type == 'gcode':
  2987. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2988. gco_list = [x for x in gco_list if x != '']
  2989. # register all keys in the Preferences window
  2990. for ext in gco_list:
  2991. new_k = new_reg_path + '.%s' % ext
  2992. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2993. # and unregister those that are no longer in the Preferences windows but are in the file
  2994. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2995. if ext not in gco_list:
  2996. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2997. # now write the updated extensions to the self.defaults
  2998. # new_ext = ''
  2999. # for ext in gco_list:
  3000. # new_ext = new_ext + ext + ', '
  3001. # self.defaults["fa_gcode"] = new_ext
  3002. self.inform.emit('[success] %s' %
  3003. _("Selected GCode file extensions registered with FlatCAM."))
  3004. if obj_type is None or obj_type == 'gerber':
  3005. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3006. grb_list = [x for x in grb_list if x != '']
  3007. # register all keys in the Preferences window
  3008. for ext in grb_list:
  3009. new_k = new_reg_path + '.%s' % ext
  3010. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3011. # and unregister those that are no longer in the Preferences windows but are in the file
  3012. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3013. if ext not in grb_list:
  3014. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3015. # now write the updated extensions to the self.defaults
  3016. # new_ext = ''
  3017. # for ext in grb_list:
  3018. # new_ext = new_ext + ext + ', '
  3019. # self.defaults["fa_gerber"] = new_ext
  3020. self.inform.emit('[success] %s' %
  3021. _("Selected Gerber file extensions registered with FlatCAM."))
  3022. def add_extension(self, ext_type):
  3023. """
  3024. Add a file extension to the list for a specific object
  3025. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3026. :return:
  3027. """
  3028. if ext_type == 'excellon':
  3029. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3030. if new_ext == '':
  3031. return
  3032. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3033. if new_ext in old_val:
  3034. return
  3035. old_val.append(new_ext)
  3036. old_val.sort()
  3037. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3038. if ext_type == 'gcode':
  3039. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3040. if new_ext == '':
  3041. return
  3042. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3043. if new_ext in old_val:
  3044. return
  3045. old_val.append(new_ext)
  3046. old_val.sort()
  3047. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3048. if ext_type == 'gerber':
  3049. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3050. if new_ext == '':
  3051. return
  3052. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3053. if new_ext in old_val:
  3054. return
  3055. old_val.append(new_ext)
  3056. old_val.sort()
  3057. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3058. if ext_type == 'keyword':
  3059. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3060. if new_kw == '':
  3061. return
  3062. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3063. if new_kw in old_val:
  3064. return
  3065. old_val.append(new_kw)
  3066. old_val.sort()
  3067. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3068. # update the self.myKeywords so the model is updated
  3069. self.autocomplete_kw_list = \
  3070. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3071. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3072. self.shell._edit.set_model_data(self.myKeywords)
  3073. def del_extension(self, ext_type):
  3074. """
  3075. Remove a file extension from the list for a specific object
  3076. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3077. :return:
  3078. """
  3079. if ext_type == 'excellon':
  3080. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3081. if new_ext == '':
  3082. return
  3083. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3084. if new_ext not in old_val:
  3085. return
  3086. old_val.remove(new_ext)
  3087. old_val.sort()
  3088. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3089. if ext_type == 'gcode':
  3090. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3091. if new_ext == '':
  3092. return
  3093. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3094. if new_ext not in old_val:
  3095. return
  3096. old_val.remove(new_ext)
  3097. old_val.sort()
  3098. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3099. if ext_type == 'gerber':
  3100. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3101. if new_ext == '':
  3102. return
  3103. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3104. if new_ext not in old_val:
  3105. return
  3106. old_val.remove(new_ext)
  3107. old_val.sort()
  3108. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3109. if ext_type == 'keyword':
  3110. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3111. if new_kw == '':
  3112. return
  3113. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3114. if new_kw not in old_val:
  3115. return
  3116. old_val.remove(new_kw)
  3117. old_val.sort()
  3118. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3119. # update the self.myKeywords so the model is updated
  3120. self.autocomplete_kw_list = \
  3121. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3122. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3123. self.shell._edit.set_model_data(self.myKeywords)
  3124. def restore_extensions(self, ext_type):
  3125. """
  3126. Restore all file extensions associations with FlatCAM, for a specific object
  3127. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3128. :return:
  3129. """
  3130. if ext_type == 'excellon':
  3131. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3132. # for the ability to open Excellon files with .txt extension
  3133. new_exc_list = deepcopy(self.exc_list)
  3134. try:
  3135. new_exc_list.remove('txt')
  3136. except ValueError:
  3137. pass
  3138. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3139. if ext_type == 'gcode':
  3140. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3141. if ext_type == 'gerber':
  3142. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3143. if ext_type == 'keyword':
  3144. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3145. # update the self.myKeywords so the model is updated
  3146. self.autocomplete_kw_list = self.default_keywords
  3147. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3148. self.shell._edit.set_model_data(self.myKeywords)
  3149. def delete_all_extensions(self, ext_type):
  3150. """
  3151. Delete all file extensions associations with FlatCAM, for a specific object
  3152. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3153. :return:
  3154. """
  3155. if ext_type == 'excellon':
  3156. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3157. if ext_type == 'gcode':
  3158. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3159. if ext_type == 'gerber':
  3160. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3161. if ext_type == 'keyword':
  3162. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3163. # update the self.myKeywords so the model is updated
  3164. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3165. self.shell._edit.set_model_data(self.myKeywords)
  3166. def on_edit_join(self, name=None):
  3167. """
  3168. Callback for Edit->Join. Joins the selected geometry objects into
  3169. a new one.
  3170. :return: None
  3171. """
  3172. self.defaults.report_usage("on_edit_join()")
  3173. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3174. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3175. geo_type_set = set()
  3176. objs = self.collection.get_selected()
  3177. if len(objs) < 2:
  3178. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3179. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3180. return 'fail'
  3181. for obj in objs:
  3182. geo_type_set.add(obj.multigeo)
  3183. # if len(geo_type_list) == 1 means that all list elements are the same
  3184. if len(geo_type_set) != 1:
  3185. self.inform.emit('[ERROR] %s' %
  3186. _("Failed join. The Geometry objects are of different types.\n"
  3187. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3188. "convert from one to another and retry joining \n"
  3189. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3190. "the result may not be what was expected. \n"
  3191. "Check the generated GCODE."))
  3192. return
  3193. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3194. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3195. if True in geo_type_set:
  3196. def initialize(geo_obj, app):
  3197. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3198. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3199. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3200. for v in geo_obj.tools.values():
  3201. v['data']['name'] = obj_name_multi
  3202. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3203. else:
  3204. def initialize(geo_obj, app):
  3205. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3206. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3207. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3208. for v in geo_obj.tools.values():
  3209. v['data']['name'] = obj_name_single
  3210. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3211. self.should_we_save = True
  3212. def on_edit_join_exc(self):
  3213. """
  3214. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3215. a new Excellon.
  3216. :return: None
  3217. """
  3218. self.defaults.report_usage("on_edit_join_exc()")
  3219. objs = self.collection.get_selected()
  3220. for obj in objs:
  3221. if not isinstance(obj, ExcellonObject):
  3222. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3223. return
  3224. if len(objs) < 2:
  3225. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3226. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3227. return 'fail'
  3228. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3229. def initialize(exc_obj, app):
  3230. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3231. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3232. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3233. self.should_we_save = True
  3234. def on_edit_join_grb(self):
  3235. """
  3236. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3237. a new Gerber object.
  3238. :return: None
  3239. """
  3240. self.defaults.report_usage("on_edit_join_grb()")
  3241. objs = self.collection.get_selected()
  3242. for obj in objs:
  3243. if not isinstance(obj, GerberObject):
  3244. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3245. return
  3246. if len(objs) < 2:
  3247. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3248. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3249. return 'fail'
  3250. def initialize(grb_obj, app):
  3251. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3252. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3253. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3254. self.should_we_save = True
  3255. def on_convert_singlegeo_to_multigeo(self):
  3256. """
  3257. Called for converting a Geometry object from single-geo to multi-geo.
  3258. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3259. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3260. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3261. the solid-geometry of that tool.
  3262. :return: None
  3263. """
  3264. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3265. obj = self.collection.get_active()
  3266. if obj is None:
  3267. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3268. return
  3269. if not isinstance(obj, GeometryObject):
  3270. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3271. return
  3272. obj.multigeo = True
  3273. for tooluid, dict_value in obj.tools.items():
  3274. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3275. if not isinstance(obj.solid_geometry, list):
  3276. obj.solid_geometry = [obj.solid_geometry]
  3277. # obj.solid_geometry[:] = []
  3278. obj.plot()
  3279. self.should_we_save = True
  3280. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3281. def on_convert_multigeo_to_singlegeo(self):
  3282. """
  3283. Called for converting a Geometry object from multi-geo to single-geo.
  3284. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3285. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3286. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3287. the solid-geometry of that tool.
  3288. :return: None
  3289. """
  3290. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3291. obj = self.collection.get_active()
  3292. if obj is None:
  3293. self.inform.emit('[ERROR_NOTCL] %s' %
  3294. _("Failed. Select a Geometry Object and try again."))
  3295. return
  3296. if not isinstance(obj, GeometryObject):
  3297. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3298. (_("Expected a GeometryObject, got"), type(obj)))
  3299. return
  3300. obj.multigeo = False
  3301. total_solid_geometry = []
  3302. for tooluid, dict_value in obj.tools.items():
  3303. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3304. # clear the original geometry
  3305. dict_value['solid_geometry'][:] = []
  3306. obj.solid_geometry = deepcopy(total_solid_geometry)
  3307. obj.plot()
  3308. self.should_we_save = True
  3309. self.inform.emit('[success] %s' %
  3310. _("A Geometry object was converted to SingleGeo type."))
  3311. def on_defaults_dict_change(self, field):
  3312. """
  3313. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3314. Edit -> Preferences tab window.
  3315. :param field: the key of the self.defaults dictionary that was changed.
  3316. :return: None
  3317. """
  3318. self.preferencesUiManager.defaults_write_form_field(field=field)
  3319. if field == "units":
  3320. self.set_screen_units(self.defaults['units'])
  3321. def set_screen_units(self, units):
  3322. """
  3323. Set the FlatCAM units on the status bar.
  3324. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3325. :return: None
  3326. """
  3327. self.ui.units_label.setText("[" + units.lower() + "]")
  3328. def on_toggle_units_click(self):
  3329. try:
  3330. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3331. except (TypeError, AttributeError):
  3332. pass
  3333. if self.defaults["units"] == 'MM':
  3334. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3335. else:
  3336. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3337. self.on_toggle_units(no_pref=True)
  3338. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3339. lambda: self.on_toggle_units(no_pref=False))
  3340. def on_toggle_units(self, no_pref=False):
  3341. """
  3342. Callback for the Units radio-button change in the Preferences tab.
  3343. Changes the application's default units adn for the project too.
  3344. If changing the project's units, the change propagates to all of
  3345. the objects in the project.
  3346. :return: None
  3347. """
  3348. self.defaults.report_usage("on_toggle_units")
  3349. if self.toggle_units_ignore:
  3350. return
  3351. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3352. # If option is the same, then ignore
  3353. if new_units == self.defaults["units"].upper():
  3354. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3355. return
  3356. # Keys in self.defaults for which to scale their values
  3357. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3358. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3359. "tools_iso_tool_vtipdia",
  3360. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3361. "gerber_editor_ma_high",
  3362. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3363. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3364. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3365. "excellon_feedrate_probe", "excellon_milling_dia",
  3366. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3367. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3368. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3369. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3370. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3371. "geometry_extracut_length", "geometry_z_pdepth",
  3372. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3373. 'cncjob_tooldia',
  3374. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3375. "tools_paintnewdia",
  3376. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3377. "tools_nccnewdia", "tools_ncc_offset_value",
  3378. "tools_2sided_drilldia",
  3379. "tools_film_boundary", "tools_film_scale_stroke",
  3380. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3381. "tools_cutout_depthperpass",
  3382. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3383. "tools_panelize_spacing_rows",
  3384. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3385. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3386. "tools_transform_buffer_dis",
  3387. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3388. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3389. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3390. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3391. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3392. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3393. "tools_cr_h2h_val", "tools_cr_dh_val",
  3394. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3395. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3396. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3397. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3398. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3399. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3400. "tools_copper_thieving_mask_clearance",
  3401. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3402. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3403. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3404. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3405. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3406. "tools_invert_margin",
  3407. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3408. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3409. def scale_defaults(sfactor):
  3410. for dim in dimensions:
  3411. if dim in [
  3412. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3413. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3414. 'tools_transform_mirror_point'
  3415. ]:
  3416. if self.defaults[dim] is None or self.defaults[dim] == '':
  3417. continue
  3418. try:
  3419. coordinates = self.defaults[dim].split(",")
  3420. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3421. coords_xy[0] *= sfactor
  3422. coords_xy[1] *= sfactor
  3423. self.defaults[dim] = "%.*f, %.*f" % (
  3424. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3425. except Exception as e:
  3426. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3427. elif dim in [
  3428. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3429. ]:
  3430. if self.defaults[dim] is None or self.defaults[dim] == '':
  3431. continue
  3432. try:
  3433. self.defaults[dim] = float(self.defaults[dim])
  3434. tools_diameters = [self.defaults[dim]]
  3435. except ValueError:
  3436. try:
  3437. tools_string = self.defaults[dim].split(",")
  3438. tools_diameters = [eval(a) for a in tools_string if a != '']
  3439. except Exception as e:
  3440. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3441. continue
  3442. self.defaults[dim] = ''
  3443. td_len = len(tools_diameters)
  3444. if td_len > 1:
  3445. for t in range(td_len):
  3446. tools_diameters[t] *= sfactor
  3447. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3448. else:
  3449. tools_diameters[0] *= sfactor
  3450. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3451. elif dim in ['global_gridx', 'global_gridy']:
  3452. # format the number of decimals to the one specified in self.decimals
  3453. try:
  3454. val = float(self.defaults[dim]) * sfactor
  3455. except Exception as e:
  3456. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3457. continue
  3458. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3459. else:
  3460. # the number of decimals for the rest is kept unchanged
  3461. if self.defaults[dim]:
  3462. try:
  3463. val = float(self.defaults[dim]) * sfactor
  3464. except Exception as e:
  3465. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3466. continue
  3467. self.defaults[dim] = val
  3468. # The scaling factor depending on choice of units.
  3469. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3470. # Changing project units. Warn user.
  3471. msgbox = QtWidgets.QMessageBox()
  3472. msgbox.setWindowTitle(_("Toggle Units"))
  3473. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3474. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3475. msgbox.setText(_("Changing the units of the project\n"
  3476. "will scale all objects.\n\n"
  3477. "Do you want to continue?"))
  3478. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3479. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3480. msgbox.setDefaultButton(bt_ok)
  3481. msgbox.exec_()
  3482. response = msgbox.clickedButton()
  3483. if response == bt_ok:
  3484. if no_pref is False:
  3485. self.preferencesUiManager.defaults_read_form()
  3486. scale_defaults(factor)
  3487. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3488. self.defaults["units"] = new_units
  3489. # update the defaults from form, some may assume that the conversion is enough and it's not
  3490. self.on_options_app2project()
  3491. # update the objects
  3492. for obj in self.collection.get_list():
  3493. obj.convert_units(new_units)
  3494. # make that the properties stored in the object are also updated
  3495. self.app_obj.object_changed.emit(obj)
  3496. # rebuild the object UI
  3497. obj.build_ui()
  3498. # change this only if the workspace is active
  3499. if self.defaults['global_workspace'] is True:
  3500. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3501. # adjust the grid values on the main toolbar
  3502. val_x = float(self.defaults['global_gridx']) * factor
  3503. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3504. current = self.collection.get_active()
  3505. if current is not None:
  3506. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3507. if not isinstance(current, GeometryObject):
  3508. current.to_form()
  3509. # replot all objects
  3510. self.plot_all()
  3511. # set the status labels to reflect the current FlatCAM units
  3512. self.set_screen_units(new_units)
  3513. # signal to the app that we changed the object properties and it should save the project
  3514. self.should_we_save = True
  3515. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3516. else:
  3517. # Undo toggling
  3518. self.toggle_units_ignore = True
  3519. if self.defaults['units'].upper() == 'MM':
  3520. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3521. else:
  3522. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3523. self.toggle_units_ignore = False
  3524. # store the grid values so they are not changed in the next step
  3525. val_x = float(self.defaults['global_gridx'])
  3526. val_y = float(self.defaults['global_gridy'])
  3527. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3528. self.preferencesUiManager.defaults_read_form()
  3529. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3530. # in self.defaults from the GUI elements but
  3531. # I don't want it for the grid values, so I update them here
  3532. self.defaults['global_gridx'] = val_x
  3533. self.defaults['global_gridy'] = val_y
  3534. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3535. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3536. def on_deselect_all(self):
  3537. self.collection.set_all_inactive()
  3538. self.delete_selection_shape()
  3539. def on_workspace_modified(self):
  3540. # self.save_defaults(silent=True)
  3541. self.plotcanvas.delete_workspace()
  3542. self.preferencesUiManager.defaults_read_form()
  3543. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3544. def on_workspace(self):
  3545. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3546. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3547. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3548. else:
  3549. self.plotcanvas.delete_workspace()
  3550. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3551. self.preferencesUiManager.defaults_read_form()
  3552. # self.save_defaults(silent=True)
  3553. def on_workspace_toggle(self):
  3554. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3555. try:
  3556. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3557. except TypeError:
  3558. pass
  3559. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3560. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3561. self.on_workspace()
  3562. def on_cursor_type(self, val):
  3563. """
  3564. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3565. :return: None
  3566. """
  3567. self.app_cursor.enabled = False
  3568. if val == 'small':
  3569. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3570. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3571. self.app_cursor = self.plotcanvas.new_cursor()
  3572. else:
  3573. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3574. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3575. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3576. if self.ui.grid_snap_btn.isChecked():
  3577. self.app_cursor.enabled = True
  3578. else:
  3579. self.app_cursor.enabled = False
  3580. def on_tool_add_keypress(self):
  3581. # ## Current application units in Upper Case
  3582. self.units = self.defaults['units'].upper()
  3583. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3584. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3585. if notebook_widget_name == 'selected_tab':
  3586. if self.collection.get_active().kind == 'geometry':
  3587. # Tool add works for Geometry only if Advanced is True in Preferences
  3588. if self.defaults["global_app_level"] == 'a':
  3589. tool_add_popup = FCInputDialog(title="New Tool ...",
  3590. text='Enter a Tool Diameter:',
  3591. min=0.0000, max=99.9999, decimals=4)
  3592. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3593. val, ok = tool_add_popup.get_value()
  3594. if ok:
  3595. if float(val) == 0:
  3596. self.inform.emit('[WARNING_NOTCL] %s' %
  3597. _("Please enter a tool diameter with non-zero value, in Float format."))
  3598. return
  3599. self.collection.get_active().on_tool_add(dia=float(val))
  3600. else:
  3601. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3602. else:
  3603. msgbox = QtWidgets.QMessageBox()
  3604. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3605. "Go to Preferences -> General - Show Advanced Options."))
  3606. msgbox.setWindowTitle("Tool adding ...")
  3607. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3608. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3609. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3610. msgbox.setDefaultButton(bt_ok)
  3611. msgbox.exec_()
  3612. # work only if the notebook tab on focus is the Tools_Tab
  3613. if notebook_widget_name == 'tool_tab':
  3614. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3615. # and only if the tool is NCC Tool
  3616. if tool_widget == self.ncclear_tool.toolName:
  3617. self.ncclear_tool.on_add_tool_by_key()
  3618. # and only if the tool is Paint Area Tool
  3619. elif tool_widget == self.paint_tool.toolName:
  3620. self.paint_tool.on_add_tool_by_key()
  3621. # and only if the tool is Solder Paste Dispensing Tool
  3622. elif tool_widget == self.paste_tool.toolName:
  3623. self.paste_tool.on_add_tool_by_key()
  3624. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3625. # See description below.
  3626. def on_delete_keypress(self):
  3627. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3628. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3629. if notebook_widget_name == 'selected_tab':
  3630. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3631. self.collection.get_active().on_tool_delete()
  3632. # work only if the notebook tab on focus is the Tools_Tab
  3633. elif notebook_widget_name == 'tool_tab':
  3634. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3635. # and only if the tool is NCC Tool
  3636. if tool_widget == self.ncclear_tool.toolName:
  3637. self.ncclear_tool.on_tool_delete()
  3638. # and only if the tool is Paint Tool
  3639. elif tool_widget == self.paint_tool.toolName:
  3640. self.paint_tool.on_tool_delete()
  3641. # and only if the tool is Solder Paste Dispensing Tool
  3642. elif tool_widget == self.paste_tool.toolName:
  3643. self.paste_tool.on_tool_delete()
  3644. # and only if the tool is Isolation Tool
  3645. elif tool_widget == self.isolation_tool.toolName:
  3646. self.isolation_tool.on_tool_delete()
  3647. else:
  3648. self.on_delete()
  3649. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3650. # some screens you have to be careful where you hover with your mouse.
  3651. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3652. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3653. # Complicated, I know :)
  3654. def on_delete(self, force_deletion=False):
  3655. """
  3656. Delete the currently selected FlatCAMObjs.
  3657. :param force_deletion: used by Tcl command
  3658. :return: None
  3659. """
  3660. self.defaults.report_usage("on_delete()")
  3661. response = None
  3662. bt_ok = None
  3663. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3664. # a geometry object before we update it.
  3665. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3666. and self.grb_editor.editor_active is False:
  3667. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3668. msgbox = QtWidgets.QMessageBox()
  3669. msgbox.setWindowTitle(_("Delete objects"))
  3670. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3671. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3672. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3673. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3674. "the selected objects?"))
  3675. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3676. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3677. msgbox.setDefaultButton(bt_ok)
  3678. msgbox.exec_()
  3679. response = msgbox.clickedButton()
  3680. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3681. response = bt_ok
  3682. if response == bt_ok:
  3683. if self.collection.get_active():
  3684. self.log.debug("App.on_delete()")
  3685. for obj_active in self.collection.get_selected():
  3686. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3687. if obj_active.kind == 'gerber':
  3688. obj_active.mark_shapes_storage.clear()
  3689. obj_active.mark_shapes.clear(update=True)
  3690. obj_active.mark_shapes.enabled = False
  3691. elif obj_active.kind == 'cncjob':
  3692. try:
  3693. obj_active.text_col.enabled = False
  3694. del obj_active.text_col
  3695. obj_active.annotation.clear(update=True)
  3696. del obj_active.annotation
  3697. except AttributeError as e:
  3698. log.debug(
  3699. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3700. )
  3701. while self.collection.get_selected():
  3702. self.delete_first_selected()
  3703. # make sure that the selection shape is deleted, too
  3704. self.delete_selection_shape()
  3705. # if there are no longer objects delete also the exclusion areas shapes
  3706. if not self.collection.get_list():
  3707. self.exc_areas.clear_shapes()
  3708. self.inform.emit('%s...' % _("Object(s) deleted"))
  3709. else:
  3710. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3711. else:
  3712. self.inform.emit(_("Save the work in Editor and try again ..."))
  3713. def delete_first_selected(self):
  3714. # Keep this for later
  3715. try:
  3716. sel_obj = self.collection.get_active()
  3717. name = sel_obj.options["name"]
  3718. isPlotted = sel_obj.options["plot"]
  3719. except AttributeError:
  3720. self.log.debug("Nothing selected for deletion")
  3721. return
  3722. if self.is_legacy is True:
  3723. # Remove plot only if the object was plotted otherwise delaxes will fail
  3724. if isPlotted:
  3725. try:
  3726. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3727. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3728. except Exception as e:
  3729. log.debug("App.delete_first_selected() --> %s" % str(e))
  3730. self.plotcanvas.auto_adjust_axes()
  3731. # Remove from dictionary
  3732. self.collection.delete_active()
  3733. # Clear form
  3734. self.setup_component_editor()
  3735. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3736. def on_set_origin(self):
  3737. """
  3738. Set the origin to the left mouse click position
  3739. :return: None
  3740. """
  3741. # display the message for the user
  3742. # and ask him to click on the desired position
  3743. self.defaults.report_usage("on_set_origin()")
  3744. def origin_replot():
  3745. def worker_task():
  3746. with self.proc_container.new('%s...' % _("Plotting")):
  3747. for obj in self.collection.get_list():
  3748. obj.plot()
  3749. self.plotcanvas.fit_view()
  3750. if self.is_legacy:
  3751. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3752. else:
  3753. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3754. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3755. self.inform.emit(_('Click to set the origin ...'))
  3756. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3757. # first disconnect it as it may have been used by something else
  3758. try:
  3759. self.replot_signal.disconnect()
  3760. except TypeError:
  3761. pass
  3762. self.replot_signal[list].connect(origin_replot)
  3763. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3764. """
  3765. :param event:
  3766. :param location:
  3767. :param noplot:
  3768. :param use_thread:
  3769. :return:
  3770. """
  3771. noplot_sig = noplot
  3772. def worker_task():
  3773. with self.proc_container.new(_("Setting Origin...")):
  3774. obj_list = self.collection.get_list()
  3775. for obj in obj_list:
  3776. obj.offset((x, y))
  3777. self.app_obj.object_changed.emit(obj)
  3778. # Update the object bounding box options
  3779. a, b, c, d = obj.bounds()
  3780. obj.options['xmin'] = a
  3781. obj.options['ymin'] = b
  3782. obj.options['xmax'] = c
  3783. obj.options['ymax'] = d
  3784. self.inform.emit('[success] %s...' % _('Origin set'))
  3785. for obj in obj_list:
  3786. out_name = obj.options["name"]
  3787. if obj.kind == 'gerber':
  3788. obj.source_file = self.export_gerber(
  3789. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3790. elif obj.kind == 'excellon':
  3791. obj.source_file = self.export_excellon(
  3792. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3793. if noplot_sig is False:
  3794. self.replot_signal.emit([])
  3795. if location is not None:
  3796. if len(location) != 2:
  3797. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3798. return 'fail'
  3799. x, y = location
  3800. if use_thread is True:
  3801. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3802. else:
  3803. worker_task()
  3804. self.should_we_save = True
  3805. return
  3806. if event is not None and event.button == 1:
  3807. if self.is_legacy is False:
  3808. event_pos = event.pos
  3809. else:
  3810. event_pos = (event.xdata, event.ydata)
  3811. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3812. if self.grid_status():
  3813. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3814. else:
  3815. pos = pos_canvas
  3816. x = 0 - pos[0]
  3817. y = 0 - pos[1]
  3818. if use_thread is True:
  3819. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3820. else:
  3821. worker_task()
  3822. self.should_we_save = True
  3823. def on_move2origin(self, use_thread=True):
  3824. """
  3825. Move selected objects to origin.
  3826. :param use_thread: Control if to use threaded operation. Boolean.
  3827. :return:
  3828. """
  3829. def worker_task():
  3830. with self.proc_container.new(_("Moving to Origin...")):
  3831. obj_list = self.collection.get_selected()
  3832. if not obj_list:
  3833. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3834. return
  3835. xminlist = []
  3836. yminlist = []
  3837. # first get a bounding box to fit all
  3838. for obj in obj_list:
  3839. xmin, ymin, xmax, ymax = obj.bounds()
  3840. xminlist.append(xmin)
  3841. yminlist.append(ymin)
  3842. # get the minimum x,y for all objects selected
  3843. x = min(xminlist)
  3844. y = min(yminlist)
  3845. for obj in obj_list:
  3846. obj.offset((-x, -y))
  3847. self.app_obj.object_changed.emit(obj)
  3848. # Update the object bounding box options
  3849. a, b, c, d = obj.bounds()
  3850. obj.options['xmin'] = a
  3851. obj.options['ymin'] = b
  3852. obj.options['xmax'] = c
  3853. obj.options['ymax'] = d
  3854. for obj in obj_list:
  3855. obj.plot()
  3856. for obj in obj_list:
  3857. out_name = obj.options["name"]
  3858. if obj.kind == 'gerber':
  3859. obj.source_file = self.export_gerber(
  3860. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3861. elif obj.kind == 'excellon':
  3862. obj.source_file = self.export_excellon(
  3863. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3864. self.inform.emit('[success] %s...' % _('Origin set'))
  3865. if use_thread is True:
  3866. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3867. else:
  3868. worker_task()
  3869. self.should_we_save = True
  3870. def on_jump_to(self, custom_location=None, fit_center=True):
  3871. """
  3872. Jump to a location by setting the mouse cursor location.
  3873. :param custom_location: Jump to a specified point. (x, y) tuple.
  3874. :param fit_center: If to fit view. Boolean.
  3875. :return:
  3876. """
  3877. self.defaults.report_usage("on_jump_to()")
  3878. if not custom_location:
  3879. dia_box_location = None
  3880. try:
  3881. dia_box_location = eval(self.clipboard.text())
  3882. except Exception:
  3883. pass
  3884. if type(dia_box_location) == tuple:
  3885. dia_box_location = str(dia_box_location)
  3886. else:
  3887. dia_box_location = None
  3888. # dia_box = Dialog_box(title=_("Jump to ..."),
  3889. # label=_("Enter the coordinates in format X,Y:"),
  3890. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3891. # initial_text=dia_box_location)
  3892. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3893. label=_("Enter the coordinates in format X,Y:"),
  3894. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3895. initial_text=dia_box_location,
  3896. reference=self.defaults['global_jump_ref'])
  3897. if dia_box.ok is True:
  3898. try:
  3899. location = eval(dia_box.location)
  3900. if not isinstance(location, tuple):
  3901. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3902. return
  3903. if dia_box.reference == 'rel':
  3904. rel_x = self.mouse[0] + location[0]
  3905. rel_y = self.mouse[1] + location[1]
  3906. location = (rel_x, rel_y)
  3907. self.defaults['global_jump_ref'] = dia_box.reference
  3908. except Exception:
  3909. return
  3910. else:
  3911. return
  3912. else:
  3913. location = custom_location
  3914. self.jump_signal.emit(location)
  3915. if fit_center:
  3916. self.plotcanvas.fit_center(loc=location)
  3917. cursor = QtGui.QCursor()
  3918. if self.is_legacy is False:
  3919. # I don't know where those differences come from but they are constant for the current
  3920. # execution of the application and they are multiples of a value around 0.0263mm.
  3921. # In a random way sometimes they are more sometimes they are less
  3922. # if units == 'MM':
  3923. # cal_factor = 0.0263
  3924. # else:
  3925. # cal_factor = 0.0263 / 25.4
  3926. cal_location = (location[0], location[1])
  3927. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3928. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3929. j_pos = (
  3930. int(canvas_origin.x() + round(jump_loc[0])),
  3931. int(canvas_origin.y() + round(jump_loc[1]))
  3932. )
  3933. cursor.setPos(j_pos[0], j_pos[1])
  3934. else:
  3935. # find the canvas origin which is in the top left corner
  3936. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3937. # determine the coordinates for the lowest left point of the canvas
  3938. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3939. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3940. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3941. # canvas) and the point (width, height) is in the top-right location
  3942. loc = self.plotcanvas.axes.transData.transform_point(location)
  3943. j_pos = (
  3944. int(x0 + loc[0]),
  3945. int(y0 - loc[1])
  3946. )
  3947. cursor.setPos(j_pos[0], j_pos[1])
  3948. self.plotcanvas.mouse = [location[0], location[1]]
  3949. if self.defaults["global_cursor_color_enabled"] is True:
  3950. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3951. else:
  3952. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3953. if self.grid_status():
  3954. # Update cursor
  3955. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3956. symbol='++', edge_color=self.cursor_color_3D,
  3957. edge_width=self.defaults["global_cursor_width"],
  3958. size=self.defaults["global_cursor_size"])
  3959. # Set the relative position label
  3960. dx = location[0] - float(self.rel_point1[0])
  3961. dy = location[1] - float(self.rel_point1[1])
  3962. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3963. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3964. # Set the position label
  3965. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3966. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3967. units = self.defaults["units"].lower()
  3968. self.plotcanvas.text_hud.text = \
  3969. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3970. dx, units, dy, units, location[0], units, location[1], units)
  3971. self.inform.emit('[success] %s' % _("Done."))
  3972. return location
  3973. def on_locate(self, obj, fit_center=True):
  3974. """
  3975. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3976. :param obj: The object on which to locate certain points
  3977. :param fit_center: If to fit view. Boolean.
  3978. :return: A point location. (x, y) tuple.
  3979. """
  3980. self.defaults.report_usage("on_locate()")
  3981. if obj is None:
  3982. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3983. return 'fail'
  3984. class DialogBoxChoice(QtWidgets.QDialog):
  3985. def __init__(self, title=None, icon=None, choice='bl'):
  3986. """
  3987. :param title: string with the window title
  3988. """
  3989. super(DialogBoxChoice, self).__init__()
  3990. self.ok = False
  3991. self.setWindowIcon(icon)
  3992. self.setWindowTitle(str(title))
  3993. self.form = QtWidgets.QFormLayout(self)
  3994. self.ref_radio = RadioSet([
  3995. {"label": _("Bottom-Left"), "value": "bl"},
  3996. {"label": _("Top-Left"), "value": "tl"},
  3997. {"label": _("Bottom-Right"), "value": "br"},
  3998. {"label": _("Top-Right"), "value": "tr"},
  3999. {"label": _("Center"), "value": "c"}
  4000. ], orientation='vertical', stretch=False)
  4001. self.ref_radio.set_value(choice)
  4002. self.form.addRow(self.ref_radio)
  4003. self.button_box = QtWidgets.QDialogButtonBox(
  4004. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4005. Qt.Horizontal, parent=self)
  4006. self.form.addRow(self.button_box)
  4007. self.button_box.accepted.connect(self.accept)
  4008. self.button_box.rejected.connect(self.reject)
  4009. if self.exec_() == QtWidgets.QDialog.Accepted:
  4010. self.ok = True
  4011. self.location_point = self.ref_radio.get_value()
  4012. else:
  4013. self.ok = False
  4014. self.location_point = None
  4015. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4016. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4017. choice=self.defaults['global_locate_pt'])
  4018. if dia_box.ok is True:
  4019. try:
  4020. location_point = dia_box.location_point
  4021. self.defaults['global_locate_pt'] = dia_box.location_point
  4022. except Exception:
  4023. return
  4024. else:
  4025. return
  4026. loc_b = obj.bounds()
  4027. if location_point == 'bl':
  4028. location = (loc_b[0], loc_b[1])
  4029. elif location_point == 'tl':
  4030. location = (loc_b[0], loc_b[3])
  4031. elif location_point == 'br':
  4032. location = (loc_b[2], loc_b[1])
  4033. elif location_point == 'tr':
  4034. location = (loc_b[2], loc_b[3])
  4035. else:
  4036. # center
  4037. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4038. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4039. location = (cx, cy)
  4040. self.locate_signal.emit(location, location_point)
  4041. if fit_center:
  4042. self.plotcanvas.fit_center(loc=location)
  4043. cursor = QtGui.QCursor()
  4044. if self.is_legacy is False:
  4045. # I don't know where those differences come from but they are constant for the current
  4046. # execution of the application and they are multiples of a value around 0.0263mm.
  4047. # In a random way sometimes they are more sometimes they are less
  4048. # if units == 'MM':
  4049. # cal_factor = 0.0263
  4050. # else:
  4051. # cal_factor = 0.0263 / 25.4
  4052. cal_location = (location[0], location[1])
  4053. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4054. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4055. j_pos = (
  4056. int(canvas_origin.x() + round(jump_loc[0])),
  4057. int(canvas_origin.y() + round(jump_loc[1]))
  4058. )
  4059. cursor.setPos(j_pos[0], j_pos[1])
  4060. else:
  4061. # find the canvas origin which is in the top left corner
  4062. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4063. # determine the coordinates for the lowest left point of the canvas
  4064. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4065. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4066. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4067. # canvas) and the point (width, height) is in the top-right location
  4068. loc = self.plotcanvas.axes.transData.transform_point(location)
  4069. j_pos = (
  4070. int(x0 + loc[0]),
  4071. int(y0 - loc[1])
  4072. )
  4073. cursor.setPos(j_pos[0], j_pos[1])
  4074. self.plotcanvas.mouse = [location[0], location[1]]
  4075. if self.defaults["global_cursor_color_enabled"] is True:
  4076. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4077. else:
  4078. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4079. if self.grid_status():
  4080. # Update cursor
  4081. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4082. symbol='++', edge_color=self.cursor_color_3D,
  4083. edge_width=self.defaults["global_cursor_width"],
  4084. size=self.defaults["global_cursor_size"])
  4085. # Set the relative position label
  4086. self.dx = location[0] - float(self.rel_point1[0])
  4087. self.dy = location[1] - float(self.rel_point1[1])
  4088. # Set the position label
  4089. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4090. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4091. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4092. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4093. units = self.defaults["units"].lower()
  4094. self.plotcanvas.text_hud.text = \
  4095. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4096. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4097. self.inform.emit('[success] %s' % _("Done."))
  4098. return location
  4099. def on_copy_command(self):
  4100. """
  4101. Will copy a selection of objects, creating new objects.
  4102. :return:
  4103. """
  4104. self.defaults.report_usage("on_copy_command()")
  4105. def initialize(obj_init, app):
  4106. """
  4107. :param obj_init: the new object
  4108. :type obj_init: class
  4109. :param app: An instance of the App class
  4110. :type app: App
  4111. :return: None
  4112. :rtype:
  4113. """
  4114. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4115. try:
  4116. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4117. except AttributeError:
  4118. pass
  4119. try:
  4120. obj_init.apertures = deepcopy(obj.apertures)
  4121. except AttributeError:
  4122. pass
  4123. try:
  4124. if obj.tools:
  4125. obj_init.tools = deepcopy(obj.tools)
  4126. except Exception as err:
  4127. log.debug("App.on_copy_command() --> %s" % str(err))
  4128. try:
  4129. obj_init.source_file = deepcopy(obj.source_file)
  4130. except (AttributeError, TypeError):
  4131. pass
  4132. def initialize_excellon(obj_init, app):
  4133. obj_init.source_file = deepcopy(obj.source_file)
  4134. obj_init.tools = deepcopy(obj.tools)
  4135. # drills are offset, so they need to be deep copied
  4136. obj_init.drills = deepcopy(obj.drills)
  4137. # slots are offset, so they need to be deep copied
  4138. obj_init.slots = deepcopy(obj.slots)
  4139. obj_init.create_geometry()
  4140. def initialize_script(obj_init, app_obj):
  4141. obj_init.source_file = deepcopy(obj.source_file)
  4142. def initialize_document(obj_init, app_obj):
  4143. obj_init.source_file = deepcopy(obj.source_file)
  4144. for obj in self.collection.get_selected():
  4145. obj_name = obj.options["name"]
  4146. try:
  4147. if isinstance(obj, ExcellonObject):
  4148. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4149. elif isinstance(obj, GerberObject):
  4150. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4151. elif isinstance(obj, GeometryObject):
  4152. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4153. elif isinstance(obj, ScriptObject):
  4154. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4155. elif isinstance(obj, DocumentObject):
  4156. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4157. except Exception as e:
  4158. return "Operation failed: %s" % str(e)
  4159. def on_copy_object2(self, custom_name):
  4160. def initialize_geometry(obj_init, app):
  4161. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4162. try:
  4163. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4164. except AttributeError:
  4165. pass
  4166. try:
  4167. obj_init.apertures = deepcopy(obj.apertures)
  4168. except AttributeError:
  4169. pass
  4170. try:
  4171. if obj.tools:
  4172. obj_init.tools = deepcopy(obj.tools)
  4173. except Exception as ee:
  4174. log.debug("on_copy_object2() --> %s" % str(ee))
  4175. def initialize_gerber(obj_init, app):
  4176. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4177. obj_init.apertures = deepcopy(obj.apertures)
  4178. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4179. def initialize_excellon(obj_init, app):
  4180. obj_init.tools = deepcopy(obj.tools)
  4181. # drills are offset, so they need to be deep copied
  4182. obj_init.drills = deepcopy(obj.drills)
  4183. # slots are offset, so they need to be deep copied
  4184. obj_init.slots = deepcopy(obj.slots)
  4185. obj_init.create_geometry()
  4186. for obj in self.collection.get_selected():
  4187. obj_name = obj.options["name"]
  4188. try:
  4189. if isinstance(obj, ExcellonObject):
  4190. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4191. elif isinstance(obj, GerberObject):
  4192. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4193. elif isinstance(obj, GeometryObject):
  4194. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4195. except Exception as er:
  4196. return "Operation failed: %s" % str(er)
  4197. def on_rename_object(self, text):
  4198. """
  4199. Will rename an object.
  4200. :param text: New name for the object.
  4201. :return:
  4202. """
  4203. self.defaults.report_usage("on_rename_object()")
  4204. named_obj = self.collection.get_active()
  4205. for obj in named_obj:
  4206. if obj is list:
  4207. self.on_rename_object(text)
  4208. else:
  4209. try:
  4210. obj.options['name'] = text
  4211. except Exception as e:
  4212. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4213. def convert_any2geo(self):
  4214. """
  4215. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4216. :return:
  4217. """
  4218. self.defaults.report_usage("convert_any2geo()")
  4219. def initialize(obj_init, app):
  4220. obj_init.solid_geometry = obj.solid_geometry
  4221. try:
  4222. obj_init.follow_geometry = obj.follow_geometry
  4223. except AttributeError:
  4224. pass
  4225. try:
  4226. obj_init.apertures = obj.apertures
  4227. except AttributeError:
  4228. pass
  4229. try:
  4230. if obj.tools:
  4231. obj_init.tools = obj.tools
  4232. except AttributeError:
  4233. pass
  4234. def initialize_excellon(obj_init, app):
  4235. # objs = self.collection.get_selected()
  4236. # GeometryObject.merge(objs, obj)
  4237. solid_geo = []
  4238. for tool in obj.tools:
  4239. for geo in obj.tools[tool]['solid_geometry']:
  4240. solid_geo.append(geo)
  4241. obj_init.solid_geometry = deepcopy(solid_geo)
  4242. if not self.collection.get_selected():
  4243. log.warning("App.convert_any2geo --> No object selected")
  4244. self.inform.emit('[WARNING_NOTCL] %s' %
  4245. _("No object is selected. Select an object and try again."))
  4246. return
  4247. for obj in self.collection.get_selected():
  4248. obj_name = obj.options["name"]
  4249. try:
  4250. if obj.kind == 'excellon':
  4251. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4252. else:
  4253. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4254. except Exception as e:
  4255. return "Operation failed: %s" % str(e)
  4256. def convert_any2gerber(self):
  4257. """
  4258. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4259. :return:
  4260. """
  4261. def initialize_geometry(obj_init, app):
  4262. apertures = {}
  4263. apid = 0
  4264. apertures[str(apid)] = {}
  4265. apertures[str(apid)]['geometry'] = []
  4266. for obj_orig in obj.solid_geometry:
  4267. new_elem = {}
  4268. new_elem['solid'] = obj_orig
  4269. try:
  4270. new_elem['follow'] = obj_orig.exterior
  4271. except AttributeError:
  4272. pass
  4273. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4274. apertures[str(apid)]['size'] = 0.0
  4275. apertures[str(apid)]['type'] = 'C'
  4276. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4277. obj_init.apertures = deepcopy(apertures)
  4278. def initialize_excellon(obj_init, app):
  4279. apertures = {}
  4280. apid = 10
  4281. for tool in obj.tools:
  4282. apertures[str(apid)] = {}
  4283. apertures[str(apid)]['geometry'] = []
  4284. for geo in obj.tools[tool]['solid_geometry']:
  4285. new_el = {}
  4286. new_el['solid'] = geo
  4287. new_el['follow'] = geo.exterior
  4288. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4289. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4290. apertures[str(apid)]['type'] = 'C'
  4291. apid += 1
  4292. # create solid_geometry
  4293. solid_geometry = []
  4294. for apid in apertures:
  4295. for geo_el in apertures[apid]['geometry']:
  4296. solid_geometry.append(geo_el['solid'])
  4297. solid_geometry = MultiPolygon(solid_geometry)
  4298. solid_geometry = solid_geometry.buffer(0.0000001)
  4299. obj_init.solid_geometry = deepcopy(solid_geometry)
  4300. obj_init.apertures = deepcopy(apertures)
  4301. # clear the working objects (perhaps not necessary due of Python GC)
  4302. apertures.clear()
  4303. if not self.collection.get_selected():
  4304. log.warning("App.convert_any2gerber --> No object selected")
  4305. self.inform.emit('[WARNING_NOTCL] %s' %
  4306. _("No object is selected. Select an object and try again."))
  4307. return
  4308. for obj in self.collection.get_selected():
  4309. obj_name = obj.options["name"]
  4310. try:
  4311. if obj.kind == 'excellon':
  4312. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4313. elif obj.kind == 'geometry':
  4314. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4315. else:
  4316. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4317. except Exception as e:
  4318. return "Operation failed: %s" % str(e)
  4319. def convert_any2excellon(self):
  4320. """
  4321. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4322. :return:
  4323. """
  4324. def initialize_geometry(obj_init, app):
  4325. tools = {}
  4326. tooluid = 1
  4327. obj_init.solid_geometry = []
  4328. for geo in obj.solid_geometry:
  4329. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4330. continue
  4331. minx, miny, maxx, maxy = geo.bounds
  4332. new_dia = min([maxx-minx, maxy-miny])
  4333. new_drill = geo.centroid
  4334. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4335. current_tooldias = []
  4336. if tools:
  4337. for tool in tools:
  4338. if tools[tool] and 'tooldia' in tools[tool]:
  4339. current_tooldias.append(tools[tool]['tooldia'])
  4340. if new_dia in current_tooldias:
  4341. for tool in tools:
  4342. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4343. new_dia)):
  4344. tools[tool]['drills'].append(new_drill)
  4345. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4346. else:
  4347. tools[tooluid] = {}
  4348. tools[tooluid]['tooldia'] = new_dia
  4349. tools[tooluid]['drills'] = [new_drill]
  4350. tools[tooluid]['slots'] = []
  4351. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4352. tooluid += 1
  4353. try:
  4354. obj_init.solid_geometry.append(new_drill_geo)
  4355. except (TypeError, AttributeError):
  4356. obj_init.solid_geometry = [new_drill_geo]
  4357. obj_init.tools = deepcopy(tools)
  4358. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4359. def initialize_gerber(obj_init, app):
  4360. tools = {}
  4361. tooluid = 1
  4362. obj_init.solid_geometry = []
  4363. for apid in obj.apertures:
  4364. if 'geometry' in obj.apertures[apid]:
  4365. for geo_dict in obj.apertures[apid]['geometry']:
  4366. if 'follow' in geo_dict:
  4367. if isinstance(geo_dict['follow'], Point):
  4368. geo = geo_dict['solid']
  4369. minx, miny, maxx, maxy = geo.bounds
  4370. new_dia = min([maxx - minx, maxy - miny])
  4371. new_drill = geo.centroid
  4372. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4373. current_tooldias = []
  4374. if tools:
  4375. for tool in tools:
  4376. if tools[tool] and 'tooldia' in tools[tool]:
  4377. current_tooldias.append(
  4378. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4379. )
  4380. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4381. for tool in tools:
  4382. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4383. '%.*f' % (self.decimals, new_dia)):
  4384. if new_drill not in tools[tool]['drills']:
  4385. tools[tool]['drills'].append(new_drill)
  4386. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4387. else:
  4388. tools[tooluid] = {}
  4389. tools[tooluid]['tooldia'] = new_dia
  4390. tools[tooluid]['drills'] = [new_drill]
  4391. tools[tooluid]['slots'] = []
  4392. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4393. tooluid += 1
  4394. try:
  4395. obj_init.solid_geometry.append(new_drill_geo)
  4396. except (TypeError, AttributeError):
  4397. obj_init.solid_geometry = [new_drill_geo]
  4398. elif isinstance(geo_dict['follow'], LineString):
  4399. geo_coords = list(geo_dict['follow'].coords)
  4400. # slots can have only a start and stop point and no intermediate points
  4401. if len(geo_coords) != 2:
  4402. continue
  4403. geo = geo_dict['solid']
  4404. try:
  4405. new_dia = obj.apertures[apid]['size']
  4406. except Exception:
  4407. continue
  4408. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4409. new_slot_geo = geo
  4410. current_tooldias = []
  4411. if tools:
  4412. for tool in tools:
  4413. if tools[tool] and 'tooldia' in tools[tool]:
  4414. current_tooldias.append(
  4415. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4416. )
  4417. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4418. for tool in tools:
  4419. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4420. '%.*f' % (self.decimals, new_dia)):
  4421. if new_slot not in tools[tool]['slots']:
  4422. tools[tool]['slots'].append(new_slot)
  4423. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4424. else:
  4425. tools[tooluid] = {}
  4426. tools[tooluid]['tooldia'] = new_dia
  4427. tools[tooluid]['drills'] = []
  4428. tools[tooluid]['slots'] = [new_slot]
  4429. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4430. tooluid += 1
  4431. try:
  4432. obj_init.solid_geometry.append(new_slot_geo)
  4433. except (TypeError, AttributeError):
  4434. obj_init.solid_geometry = [new_slot_geo]
  4435. obj_init.tools = deepcopy(tools)
  4436. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4437. if not self.collection.get_selected():
  4438. log.warning("App.convert_any2excellon--> No object selected")
  4439. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4440. return
  4441. for obj in self.collection.get_selected():
  4442. obj_name = obj.options["name"]
  4443. try:
  4444. if obj.kind == 'gerber':
  4445. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4446. elif obj.kind == 'geometry':
  4447. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4448. else:
  4449. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4450. except Exception as e:
  4451. return "Operation failed: %s" % str(e)
  4452. def abort_all_tasks(self):
  4453. """
  4454. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4455. on the first possible occasion.
  4456. :return:
  4457. """
  4458. if self.abort_flag is False:
  4459. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4460. self.abort_flag = True
  4461. self.cleanup.emit()
  4462. def app_is_idle(self):
  4463. if self.abort_flag:
  4464. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4465. self.abort_flag = False
  4466. def on_selectall(self):
  4467. """
  4468. Will draw a selection box shape around the selected objects.
  4469. :return:
  4470. """
  4471. self.defaults.report_usage("on_selectall()")
  4472. # delete the possible selection box around a possible selected object
  4473. self.delete_selection_shape()
  4474. for name in self.collection.get_names():
  4475. self.collection.set_active(name)
  4476. curr_sel_obj = self.collection.get_by_name(name)
  4477. # create the selection box around the selected object
  4478. if self.defaults['global_selection_shape'] is True:
  4479. self.draw_selection_shape(curr_sel_obj)
  4480. def on_toggle_preferences(self):
  4481. pref_open = False
  4482. for idx in range(self.ui.plot_tab_area.count()):
  4483. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4484. pref_open = True
  4485. if pref_open:
  4486. for idx in range(self.ui.plot_tab_area.count()):
  4487. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4488. self.ui.plot_tab_area.removeTab(idx)
  4489. break
  4490. self.ui.pref_status_label.setStyleSheet("")
  4491. else:
  4492. self.on_preferences()
  4493. def on_preferences(self):
  4494. """
  4495. Adds the Preferences in a Tab in Plot Area
  4496. :return:
  4497. """
  4498. # add the tab if it was closed
  4499. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4500. # delete the absolute and relative position and messages in the infobar
  4501. # self.ui.position_label.setText("")
  4502. # self.ui.rel_position_label.setText("")
  4503. # hide coordinates toolbars in the infobar while in DB
  4504. self.ui.coords_toolbar.hide()
  4505. self.ui.delta_coords_toolbar.hide()
  4506. # Switch plot_area to preferences page
  4507. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4508. # self.ui.show()
  4509. self.ui.pref_status_label.setStyleSheet("""
  4510. QLabel
  4511. {
  4512. color: black;
  4513. background-color: lightseagreen;
  4514. }
  4515. """
  4516. )
  4517. # detect changes in the preferences
  4518. for idx in range(self.ui.pref_tab_area.count()):
  4519. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4520. try:
  4521. try:
  4522. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4523. except (TypeError, AttributeError):
  4524. pass
  4525. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4526. except AttributeError:
  4527. pass
  4528. try:
  4529. try:
  4530. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4531. except (TypeError, AttributeError):
  4532. pass
  4533. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4534. except AttributeError:
  4535. pass
  4536. try:
  4537. try:
  4538. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4539. except (TypeError, AttributeError):
  4540. pass
  4541. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4542. except AttributeError:
  4543. pass
  4544. try:
  4545. try:
  4546. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4547. except (TypeError, AttributeError):
  4548. pass
  4549. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4550. except AttributeError:
  4551. pass
  4552. try:
  4553. try:
  4554. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4555. except (TypeError, AttributeError):
  4556. pass
  4557. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4558. except AttributeError:
  4559. pass
  4560. def on_tools_database(self, source='app'):
  4561. """
  4562. Adds the Tools Database in a Tab in Plot Area.
  4563. :return:
  4564. """
  4565. for idx in range(self.ui.plot_tab_area.count()):
  4566. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4567. # there can be only one instance of Tools Database at one time
  4568. return
  4569. if source == 'app':
  4570. self.tools_db_tab = ToolsDB2(
  4571. app=self,
  4572. parent=self.ui,
  4573. callback_on_edited=self.on_tools_db_edited,
  4574. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4575. )
  4576. elif source == 'ncc':
  4577. self.tools_db_tab = ToolsDB2(
  4578. app=self,
  4579. parent=self.ui,
  4580. callback_on_edited=self.on_tools_db_edited,
  4581. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4582. )
  4583. elif source == 'paint':
  4584. self.tools_db_tab = ToolsDB2(
  4585. app=self,
  4586. parent=self.ui,
  4587. callback_on_edited=self.on_tools_db_edited,
  4588. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4589. )
  4590. elif source == 'iso':
  4591. self.tools_db_tab = ToolsDB2(
  4592. app=self,
  4593. parent=self.ui,
  4594. callback_on_edited=self.on_tools_db_edited,
  4595. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4596. )
  4597. # add the tab if it was closed
  4598. try:
  4599. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4600. self.tools_db_tab.setObjectName("database_tab")
  4601. except Exception as e:
  4602. log.debug("App.on_tools_database() --> %s" % str(e))
  4603. return
  4604. # delete the absolute and relative position and messages in the infobar
  4605. # self.ui.position_label.setText("")
  4606. # self.ui.rel_position_label.setText("")
  4607. # hide coordinates toolbars in the infobar while in DB
  4608. self.ui.coords_toolbar.hide()
  4609. self.ui.delta_coords_toolbar.hide()
  4610. # Switch plot_area to preferences page
  4611. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4612. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4613. self.tools_db_tab.ui_connect()
  4614. def on_tools_db_edited(self):
  4615. """
  4616. Executed whenever a tool is edited in Tools Database.
  4617. Will color the text of the Tools Database tab to Red color.
  4618. :return:
  4619. """
  4620. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4621. for idx in range(self.ui.plot_tab_area.count()):
  4622. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4623. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4624. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4625. self.tools_db_changed_flag = True
  4626. def on_geometry_tool_add_from_db_executed(self, tool):
  4627. """
  4628. Here add the tool from DB in the selected geometry object.
  4629. :return:
  4630. """
  4631. tool_from_db = deepcopy(tool)
  4632. obj = self.collection.get_active()
  4633. if obj.kind == 'geometry':
  4634. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4635. # close the tab and delete it
  4636. for idx in range(self.ui.plot_tab_area.count()):
  4637. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4638. wdg = self.ui.plot_tab_area.widget(idx)
  4639. wdg.deleteLater()
  4640. self.ui.plot_tab_area.removeTab(idx)
  4641. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4642. elif obj.kind == 'gerber':
  4643. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4644. # close the tab and delete it
  4645. for idx in range(self.ui.plot_tab_area.count()):
  4646. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4647. wdg = self.ui.plot_tab_area.widget(idx)
  4648. wdg.deleteLater()
  4649. self.ui.plot_tab_area.removeTab(idx)
  4650. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4651. else:
  4652. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4653. def on_plot_area_tab_closed(self, tab_obj_name):
  4654. """
  4655. Executed whenever a QTab is closed in the Plot Area.
  4656. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4657. :return:
  4658. """
  4659. if tab_obj_name == "preferences_tab":
  4660. self.preferencesUiManager.on_close_preferences_tab()
  4661. elif tab_obj_name == "database_tab":
  4662. # disconnect the signals from the table widget in tab
  4663. self.tools_db_tab.ui_disconnect()
  4664. if self.tools_db_changed_flag is True:
  4665. msgbox = QtWidgets.QMessageBox()
  4666. msgbox.setText(_("One or more Tools are edited.\n"
  4667. "Do you want to update the Tools Database?"))
  4668. msgbox.setWindowTitle(_("Save Tools Database"))
  4669. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4670. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4671. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4672. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4673. msgbox.setDefaultButton(bt_yes)
  4674. msgbox.exec_()
  4675. response = msgbox.clickedButton()
  4676. if response == bt_yes:
  4677. self.tools_db_tab.on_save_tools_db()
  4678. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4679. else:
  4680. self.tools_db_changed_flag = False
  4681. self.inform.emit('')
  4682. return
  4683. self.tools_db_tab.deleteLater()
  4684. elif tab_obj_name == "text_editor_tab":
  4685. self.toggle_codeeditor = False
  4686. elif tab_obj_name == "bookmarks_tab":
  4687. self.book_dialog_tab.rebuild_actions()
  4688. self.book_dialog_tab.deleteLater()
  4689. else:
  4690. pass
  4691. # restore the coords toolbars
  4692. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4693. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4694. def on_flipy(self):
  4695. """
  4696. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4697. :return:
  4698. """
  4699. self.defaults.report_usage("on_flipy()")
  4700. obj_list = self.collection.get_selected()
  4701. xminlist = []
  4702. yminlist = []
  4703. xmaxlist = []
  4704. ymaxlist = []
  4705. if not obj_list:
  4706. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4707. else:
  4708. try:
  4709. # first get a bounding box to fit all
  4710. for obj in obj_list:
  4711. xmin, ymin, xmax, ymax = obj.bounds()
  4712. xminlist.append(xmin)
  4713. yminlist.append(ymin)
  4714. xmaxlist.append(xmax)
  4715. ymaxlist.append(ymax)
  4716. # get the minimum x,y and maximum x,y for all objects selected
  4717. xminimal = min(xminlist)
  4718. yminimal = min(yminlist)
  4719. xmaximal = max(xmaxlist)
  4720. ymaximal = max(ymaxlist)
  4721. px = 0.5 * (xminimal + xmaximal)
  4722. py = 0.5 * (yminimal + ymaximal)
  4723. # execute mirroring
  4724. for obj in obj_list:
  4725. obj.mirror('X', [px, py])
  4726. obj.plot()
  4727. self.app_obj.object_changed.emit(obj)
  4728. self.inform.emit('[success] %s' %
  4729. _("Flip on Y axis done."))
  4730. except Exception as e:
  4731. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4732. return
  4733. def on_flipx(self):
  4734. """
  4735. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4736. :return:
  4737. """
  4738. self.defaults.report_usage("on_flipx()")
  4739. obj_list = self.collection.get_selected()
  4740. xminlist = []
  4741. yminlist = []
  4742. xmaxlist = []
  4743. ymaxlist = []
  4744. if not obj_list:
  4745. self.inform.emit('[WARNING_NOTCL] %s' %
  4746. _("No object selected to Flip on X axis."))
  4747. else:
  4748. try:
  4749. # first get a bounding box to fit all
  4750. for obj in obj_list:
  4751. xmin, ymin, xmax, ymax = obj.bounds()
  4752. xminlist.append(xmin)
  4753. yminlist.append(ymin)
  4754. xmaxlist.append(xmax)
  4755. ymaxlist.append(ymax)
  4756. # get the minimum x,y and maximum x,y for all objects selected
  4757. xminimal = min(xminlist)
  4758. yminimal = min(yminlist)
  4759. xmaximal = max(xmaxlist)
  4760. ymaximal = max(ymaxlist)
  4761. px = 0.5 * (xminimal + xmaximal)
  4762. py = 0.5 * (yminimal + ymaximal)
  4763. # execute mirroring
  4764. for obj in obj_list:
  4765. obj.mirror('Y', [px, py])
  4766. obj.plot()
  4767. self.app_obj.object_changed.emit(obj)
  4768. self.inform.emit('[success] %s' %
  4769. _("Flip on X axis done."))
  4770. except Exception as e:
  4771. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4772. return
  4773. def on_rotate(self, silent=False, preset=None):
  4774. """
  4775. Executed when Options -> Rotate Selection menu entry is clicked.
  4776. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4777. :param preset: A value to be used as predefined angle for rotation.
  4778. :return:
  4779. """
  4780. self.defaults.report_usage("on_rotate()")
  4781. obj_list = self.collection.get_selected()
  4782. xminlist = []
  4783. yminlist = []
  4784. xmaxlist = []
  4785. ymaxlist = []
  4786. if not obj_list:
  4787. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4788. else:
  4789. if silent is False:
  4790. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4791. min=-360, max=360, decimals=4,
  4792. init_val=float(self.defaults['tools_transform_rotate']))
  4793. num, ok = rotatebox.get_value()
  4794. else:
  4795. num = preset
  4796. ok = True
  4797. if ok:
  4798. try:
  4799. # first get a bounding box to fit all
  4800. for obj in obj_list:
  4801. xmin, ymin, xmax, ymax = obj.bounds()
  4802. xminlist.append(xmin)
  4803. yminlist.append(ymin)
  4804. xmaxlist.append(xmax)
  4805. ymaxlist.append(ymax)
  4806. # get the minimum x,y and maximum x,y for all objects selected
  4807. xminimal = min(xminlist)
  4808. yminimal = min(yminlist)
  4809. xmaximal = max(xmaxlist)
  4810. ymaximal = max(ymaxlist)
  4811. px = 0.5 * (xminimal + xmaximal)
  4812. py = 0.5 * (yminimal + ymaximal)
  4813. for sel_obj in obj_list:
  4814. sel_obj.rotate(-float(num), point=(px, py))
  4815. sel_obj.plot()
  4816. self.app_obj.object_changed.emit(sel_obj)
  4817. self.inform.emit('[success] %s' % _("Rotation done."))
  4818. except Exception as e:
  4819. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4820. return
  4821. def on_skewx(self):
  4822. """
  4823. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4824. :return:
  4825. """
  4826. self.defaults.report_usage("on_skewx()")
  4827. obj_list = self.collection.get_selected()
  4828. xminlist = []
  4829. yminlist = []
  4830. if not obj_list:
  4831. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4832. else:
  4833. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4834. min=-360, max=360, decimals=4,
  4835. init_val=float(self.defaults['tools_transform_skew_x']))
  4836. num, ok = skewxbox.get_value()
  4837. if ok:
  4838. # first get a bounding box to fit all
  4839. for obj in obj_list:
  4840. xmin, ymin, xmax, ymax = obj.bounds()
  4841. xminlist.append(xmin)
  4842. yminlist.append(ymin)
  4843. # get the minimum x,y and maximum x,y for all objects selected
  4844. xminimal = min(xminlist)
  4845. yminimal = min(yminlist)
  4846. for obj in obj_list:
  4847. obj.skew(num, 0, point=(xminimal, yminimal))
  4848. obj.plot()
  4849. self.app_obj.object_changed.emit(obj)
  4850. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4851. def on_skewy(self):
  4852. """
  4853. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4854. :return:
  4855. """
  4856. self.defaults.report_usage("on_skewy()")
  4857. obj_list = self.collection.get_selected()
  4858. xminlist = []
  4859. yminlist = []
  4860. if not obj_list:
  4861. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4862. else:
  4863. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4864. min=-360, max=360, decimals=4,
  4865. init_val=float(self.defaults['tools_transform_skew_y']))
  4866. num, ok = skewybox.get_value()
  4867. if ok:
  4868. # first get a bounding box to fit all
  4869. for obj in obj_list:
  4870. xmin, ymin, xmax, ymax = obj.bounds()
  4871. xminlist.append(xmin)
  4872. yminlist.append(ymin)
  4873. # get the minimum x,y and maximum x,y for all objects selected
  4874. xminimal = min(xminlist)
  4875. yminimal = min(yminlist)
  4876. for obj in obj_list:
  4877. obj.skew(0, num, point=(xminimal, yminimal))
  4878. obj.plot()
  4879. self.app_obj.object_changed.emit(obj)
  4880. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4881. def on_plots_updated(self):
  4882. """
  4883. Callback used to report when the plots have changed.
  4884. Adjust axes and zooms to fit.
  4885. :return: None
  4886. """
  4887. if self.is_legacy is False:
  4888. self.plotcanvas.update()
  4889. else:
  4890. self.plotcanvas.auto_adjust_axes()
  4891. self.on_zoom_fit()
  4892. self.collection.update_view()
  4893. # self.inform.emit(_("Plots updated ..."))
  4894. def on_toolbar_replot(self):
  4895. """
  4896. Callback for toolbar button. Re-plots all objects.
  4897. :return: None
  4898. """
  4899. self.log.debug("on_toolbar_replot()")
  4900. try:
  4901. obj = self.collection.get_active()
  4902. if obj:
  4903. obj.read_form()
  4904. else:
  4905. self.on_zoom_fit()
  4906. except AttributeError as e:
  4907. log.debug("on_toolbar_replot() -> %s" % str(e))
  4908. pass
  4909. self.plot_all()
  4910. def grid_status(self):
  4911. return True if self.ui.grid_snap_btn.isChecked() else False
  4912. def populate_cmenu_grids(self):
  4913. units = self.defaults['units'].lower()
  4914. # for act in self.ui.cmenu_gridmenu.actions():
  4915. # act.triggered.disconnect()
  4916. self.ui.cmenu_gridmenu.clear()
  4917. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4918. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4919. _("Grid On/Off"))
  4920. grid_toggle.setCheckable(True)
  4921. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4922. self.ui.cmenu_gridmenu.addSeparator()
  4923. for grid in sorted_list:
  4924. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4925. "%s" % str(grid))
  4926. action.triggered.connect(self.set_grid)
  4927. self.ui.cmenu_gridmenu.addSeparator()
  4928. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4929. _("Add"))
  4930. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4931. _("Delete"))
  4932. grid_add.triggered.connect(self.on_grid_add)
  4933. grid_delete.triggered.connect(self.on_grid_delete)
  4934. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4935. def set_grid(self):
  4936. menu_action = self.sender()
  4937. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4938. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4939. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4940. def on_grid_add(self):
  4941. # ## Current application units in lower Case
  4942. units = self.defaults['units'].lower()
  4943. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4944. text=_('Enter a Grid Value:'),
  4945. min=0.0000, max=99.9999, decimals=4)
  4946. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4947. val, ok = grid_add_popup.get_value()
  4948. if ok:
  4949. if float(val) == 0:
  4950. self.inform.emit('[WARNING_NOTCL] %s' %
  4951. _("Please enter a grid value with non-zero value, in Float format."))
  4952. return
  4953. else:
  4954. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4955. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4956. self.inform.emit('[success] %s...' % _("New Grid added"))
  4957. else:
  4958. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4959. else:
  4960. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4961. def on_grid_delete(self):
  4962. # ## Current application units in lower Case
  4963. units = self.defaults['units'].lower()
  4964. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4965. text='Enter a Grid Value:',
  4966. min=0.0000, max=99.9999, decimals=4)
  4967. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4968. val, ok = grid_del_popup.get_value()
  4969. if ok:
  4970. if float(val) == 0:
  4971. self.inform.emit('[WARNING_NOTCL] %s' %
  4972. _("Please enter a grid value with non-zero value, in Float format."))
  4973. return
  4974. else:
  4975. try:
  4976. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4977. except ValueError:
  4978. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4979. return
  4980. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4981. else:
  4982. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4983. def on_shortcut_list(self):
  4984. self.defaults.report_usage("on_shortcut_list()")
  4985. # add the tab if it was closed
  4986. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4987. # delete the absolute and relative position and messages in the infobar
  4988. # self.ui.position_label.setText("")
  4989. # self.ui.rel_position_label.setText("")
  4990. # hide coordinates toolbars in the infobar while in DB
  4991. self.ui.coords_toolbar.hide()
  4992. self.ui.delta_coords_toolbar.hide()
  4993. # Switch plot_area to preferences page
  4994. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4995. # self.ui.show()
  4996. def on_select_tab(self, name):
  4997. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4998. if self.ui.splitter.sizes()[0] == 0:
  4999. self.ui.splitter.setSizes([1, 1])
  5000. else:
  5001. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5002. self.ui.splitter.setSizes([0, 1])
  5003. if name == 'project':
  5004. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5005. elif name == 'selected':
  5006. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5007. elif name == 'tool':
  5008. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5009. def on_copy_name(self):
  5010. self.defaults.report_usage("on_copy_name()")
  5011. obj = self.collection.get_active()
  5012. try:
  5013. name = obj.options["name"]
  5014. except AttributeError:
  5015. log.debug("on_copy_name() --> No object selected to copy it's name")
  5016. self.inform.emit('[WARNING_NOTCL] %s' %
  5017. _(" No object selected to copy it's name"))
  5018. return
  5019. self.clipboard.setText(name)
  5020. self.inform.emit(_("Name copied on clipboard ..."))
  5021. def on_mouse_click_over_plot(self, event):
  5022. """
  5023. Default actions are:
  5024. :param event: Contains information about the event, like which button
  5025. was clicked, the pixel coordinates and the axes coordinates.
  5026. :return: None
  5027. """
  5028. self.pos = []
  5029. if self.is_legacy is False:
  5030. event_pos = event.pos
  5031. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5032. # # Set the mouse button for panning
  5033. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5034. else:
  5035. event_pos = (event.xdata, event.ydata)
  5036. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5037. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5038. # So it can receive key presses
  5039. self.plotcanvas.native.setFocus()
  5040. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5041. if self.grid_status():
  5042. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5043. else:
  5044. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5045. try:
  5046. if event.button == 1:
  5047. # Reset here the relative coordinates so there is a new reference on the click position
  5048. if self.rel_point1 is None:
  5049. self.rel_point1 = self.pos
  5050. else:
  5051. self.rel_point2 = copy(self.rel_point1)
  5052. self.rel_point1 = self.pos
  5053. self.on_mouse_move_over_plot(event, origin_click=True)
  5054. except Exception as e:
  5055. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5056. def on_mouse_double_click_over_plot(self, event):
  5057. if event.button == 1:
  5058. self.doubleclick = True
  5059. def on_mouse_move_over_plot(self, event, origin_click=None):
  5060. """
  5061. Callback for the mouse motion event over the plot.
  5062. :param event: Contains information about the event.
  5063. :param origin_click
  5064. :return: None
  5065. """
  5066. if self.is_legacy is False:
  5067. event_pos = event.pos
  5068. if self.defaults["global_pan_button"] == '2':
  5069. pan_button = 2
  5070. else:
  5071. pan_button = 3
  5072. self.event_is_dragging = event.is_dragging
  5073. else:
  5074. event_pos = (event.xdata, event.ydata)
  5075. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5076. if self.defaults["global_pan_button"] == '2':
  5077. pan_button = 3
  5078. else:
  5079. pan_button = 2
  5080. self.event_is_dragging = self.plotcanvas.is_dragging
  5081. # So it can receive key presses but not when the Tcl Shell is active
  5082. if not self.ui.shell_dock.isVisible():
  5083. if not self.plotcanvas.native.hasFocus():
  5084. self.plotcanvas.native.setFocus()
  5085. self.pos_jump = event_pos
  5086. self.ui.popMenu.mouse_is_panning = False
  5087. if origin_click is None:
  5088. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5089. if event.button == pan_button and self.event_is_dragging == 1:
  5090. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5091. if self.ui.popMenu.popup_active:
  5092. self.ui.popMenu.popup_active = False
  5093. return
  5094. self.ui.popMenu.mouse_is_panning = True
  5095. return
  5096. if self.rel_point1 is not None:
  5097. try: # May fail in case mouse not within axes
  5098. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5099. if pos_canvas[0] is None or pos_canvas[1] is None:
  5100. return
  5101. if self.grid_status():
  5102. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5103. # Update cursor
  5104. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5105. symbol='++', edge_color=self.cursor_color_3D,
  5106. edge_width=self.defaults["global_cursor_width"],
  5107. size=self.defaults["global_cursor_size"])
  5108. else:
  5109. pos = (pos_canvas[0], pos_canvas[1])
  5110. self.dx = pos[0] - float(self.rel_point1[0])
  5111. self.dy = pos[1] - float(self.rel_point1[1])
  5112. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5113. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5114. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5115. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5116. units = self.defaults["units"].lower()
  5117. self.plotcanvas.text_hud.text = \
  5118. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5119. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5120. self.mouse = [pos[0], pos[1]]
  5121. if self.defaults['global_selection_shape'] is False:
  5122. self.selection_type = None
  5123. return
  5124. # if the mouse is moved and the LMB is clicked then the action is a selection
  5125. if self.event_is_dragging == 1 and event.button == 1:
  5126. self.delete_selection_shape()
  5127. if self.dx < 0:
  5128. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5129. face_color=self.defaults['global_alt_sel_fill'])
  5130. self.selection_type = False
  5131. elif self.dx >= 0:
  5132. self.draw_moving_selection_shape(self.pos, pos)
  5133. self.selection_type = True
  5134. else:
  5135. self.selection_type = None
  5136. else:
  5137. self.selection_type = None
  5138. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5139. if self.defaults['global_hover']:
  5140. for obj in self.collection.get_list():
  5141. try:
  5142. # select the object(s) only if it is enabled (plotted)
  5143. if obj.options['plot']:
  5144. if obj not in self.collection.get_selected():
  5145. poly_obj = Polygon(
  5146. [(obj.options['xmin'], obj.options['ymin']),
  5147. (obj.options['xmax'], obj.options['ymin']),
  5148. (obj.options['xmax'], obj.options['ymax']),
  5149. (obj.options['xmin'], obj.options['ymax'])]
  5150. )
  5151. if Point(pos).within(poly_obj):
  5152. if obj.isHovering is False:
  5153. obj.isHovering = True
  5154. obj.notHovering = True
  5155. # create the selection box around the selected object
  5156. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5157. else:
  5158. if obj.notHovering is True:
  5159. obj.notHovering = False
  5160. obj.isHovering = False
  5161. self.delete_hover_shape()
  5162. except Exception:
  5163. # the Exception here will happen if we try to select on screen and we have an
  5164. # newly (and empty) just created Geometry or Excellon object that do not have the
  5165. # xmin, xmax, ymin, ymax options.
  5166. # In this case poly_obj creation (see above) will fail
  5167. pass
  5168. except Exception as e:
  5169. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5170. self.ui.position_label.setText("")
  5171. self.ui.rel_position_label.setText("")
  5172. self.mouse = None
  5173. def on_mouse_click_release_over_plot(self, event):
  5174. """
  5175. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5176. and has been registered in ''self.__init__()''.
  5177. :param event: contains information about the event.
  5178. :return:
  5179. """
  5180. if self.is_legacy is False:
  5181. event_pos = event.pos
  5182. right_button = 2
  5183. else:
  5184. event_pos = (event.xdata, event.ydata)
  5185. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5186. right_button = 3
  5187. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5188. if self.grid_status():
  5189. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5190. else:
  5191. pos = (pos_canvas[0], pos_canvas[1])
  5192. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5193. # canvas menu
  5194. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5195. self.ui.popMenu.mouse_is_panning = False
  5196. self.cursor = QtGui.QCursor()
  5197. self.populate_cmenu_grids()
  5198. self.ui.popMenu.popup(self.cursor.pos())
  5199. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5200. # selection and then select a type of selection ("enclosing" or "touching")
  5201. if event.button == 1: # left click
  5202. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5203. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5204. if modifiers == QtCore.Qt.ShiftModifier:
  5205. # do not auto open the Project Tab
  5206. self.click_noproject = True
  5207. self.clipboard.setText(
  5208. self.defaults["global_point_clipboard_format"] %
  5209. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5210. )
  5211. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5212. return
  5213. if self.doubleclick is True:
  5214. self.doubleclick = False
  5215. if self.collection.get_selected():
  5216. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5217. if self.ui.splitter.sizes()[0] == 0:
  5218. self.ui.splitter.setSizes([1, 1])
  5219. try:
  5220. # delete the selection shape(S) as it may be in the way
  5221. self.delete_selection_shape()
  5222. self.delete_hover_shape()
  5223. except Exception as e:
  5224. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5225. return
  5226. else:
  5227. # WORKAROUND for LEGACY MODE
  5228. if self.is_legacy is True:
  5229. # if there is no move on canvas then we have no dragging selection
  5230. if self.dx == 0 or self.dy == 0:
  5231. self.selection_type = None
  5232. if self.selection_type is not None:
  5233. try:
  5234. self.selection_area_handler(self.pos, pos, self.selection_type)
  5235. self.selection_type = None
  5236. except Exception as e:
  5237. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5238. return
  5239. else:
  5240. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5241. if key_modifier == QtCore.Qt.ShiftModifier:
  5242. mod_key = 'Shift'
  5243. elif key_modifier == QtCore.Qt.ControlModifier:
  5244. mod_key = 'Control'
  5245. else:
  5246. mod_key = None
  5247. try:
  5248. if self.command_active is None:
  5249. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5250. # deselect, and if it's not selected then it will be selected
  5251. # If there is no active command (self.command_active is None) then we check if we clicked
  5252. # on a object by checking the bounding limits against mouse click position
  5253. if mod_key == self.defaults["global_mselect_key"]:
  5254. self.select_objects(key='multisel')
  5255. else:
  5256. # If there is no active command (self.command_active is None) then we check if
  5257. # we clicked on a object by checking the bounding limits against mouse click position
  5258. self.select_objects()
  5259. self.delete_hover_shape()
  5260. except Exception as e:
  5261. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5262. return
  5263. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5264. """
  5265. :param start_pos: mouse position when the selection LMB click was done
  5266. :param end_pos: mouse position when the left mouse button is released
  5267. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5268. :return:
  5269. """
  5270. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5271. # delete previous selection shape
  5272. self.delete_selection_shape()
  5273. # make all objects inactive
  5274. self.collection.set_all_inactive()
  5275. for obj in self.collection.get_list():
  5276. try:
  5277. # select the object(s) only if it is enabled (plotted)
  5278. if obj.options['plot']:
  5279. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5280. (obj.options['xmax'], obj.options['ymin']),
  5281. (obj.options['xmax'], obj.options['ymax']),
  5282. (obj.options['xmin'], obj.options['ymax'])])
  5283. if sel_type is True:
  5284. if poly_obj.within(poly_selection):
  5285. # create the selection box around the selected object
  5286. if self.defaults['global_selection_shape'] is True:
  5287. self.draw_selection_shape(obj)
  5288. self.collection.set_active(obj.options['name'])
  5289. else:
  5290. if poly_selection.intersects(poly_obj):
  5291. # create the selection box around the selected object
  5292. if self.defaults['global_selection_shape'] is True:
  5293. self.draw_selection_shape(obj)
  5294. self.collection.set_active(obj.options['name'])
  5295. obj.selection_shape_drawn = True
  5296. except Exception as e:
  5297. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5298. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5299. # In this case poly_obj creation (see above) will fail
  5300. log.debug("App.selection_area_handler() --> %s" % str(e))
  5301. def select_objects(self, key=None):
  5302. """
  5303. Will select objects clicked on canvas
  5304. :param key: for future use in cumulative selection
  5305. :return:
  5306. """
  5307. # list where we store the overlapped objects under our mouse left click position
  5308. if key is None:
  5309. self.objects_under_the_click_list = []
  5310. # Populate the list with the overlapped objects on the click position
  5311. curr_x, curr_y = self.pos
  5312. for obj in self.all_objects_list:
  5313. # ScriptObject and DocumentObject objects can't be selected
  5314. if obj.kind == 'script' or obj.kind == 'document':
  5315. continue
  5316. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5317. continue
  5318. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5319. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5320. if obj.options['name'] not in self.objects_under_the_click_list:
  5321. if obj.options['plot']:
  5322. # add objects to the objects_under_the_click list only if the object is plotted
  5323. # (active and not disabled)
  5324. self.objects_under_the_click_list.append(obj.options['name'])
  5325. try:
  5326. if self.objects_under_the_click_list:
  5327. curr_sel_obj = self.collection.get_active()
  5328. # case when there is only an object under the click and we toggle it
  5329. if len(self.objects_under_the_click_list) == 1:
  5330. if curr_sel_obj is None:
  5331. self.collection.set_active(self.objects_under_the_click_list[0])
  5332. curr_sel_obj = self.collection.get_active()
  5333. # create the selection box around the selected object
  5334. if self.defaults['global_selection_shape'] is True:
  5335. self.draw_selection_shape(curr_sel_obj)
  5336. curr_sel_obj.selection_shape_drawn = True
  5337. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5338. self.collection.on_objects_selection(False)
  5339. self.delete_selection_shape()
  5340. curr_sel_obj.selection_shape_drawn = False
  5341. self.collection.set_active(self.objects_under_the_click_list[0])
  5342. curr_sel_obj = self.collection.get_active()
  5343. # create the selection box around the selected object
  5344. if self.defaults['global_selection_shape'] is True:
  5345. self.draw_selection_shape(curr_sel_obj)
  5346. curr_sel_obj.selection_shape_drawn = True
  5347. self.selected_message(curr_sel_obj=curr_sel_obj)
  5348. elif curr_sel_obj.selection_shape_drawn is False:
  5349. if self.defaults['global_selection_shape'] is True:
  5350. self.draw_selection_shape(curr_sel_obj)
  5351. curr_sel_obj.selection_shape_drawn = True
  5352. else:
  5353. self.collection.on_objects_selection(False)
  5354. self.delete_selection_shape()
  5355. if self.call_source != 'app':
  5356. self.call_source = 'app'
  5357. self.selected_message(curr_sel_obj=curr_sel_obj)
  5358. else:
  5359. # If there is no selected object
  5360. # make active the first element of the overlapped objects list
  5361. if self.collection.get_active() is None:
  5362. self.collection.set_active(self.objects_under_the_click_list[0])
  5363. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5364. name_sel_obj = self.collection.get_active().options['name']
  5365. # In case that there is a selected object but it is not in the overlapped object list
  5366. # make that object inactive and activate the first element in the overlapped object list
  5367. if name_sel_obj not in self.objects_under_the_click_list:
  5368. self.collection.set_inactive(name_sel_obj)
  5369. name_sel_obj = self.objects_under_the_click_list[0]
  5370. self.collection.set_active(name_sel_obj)
  5371. else:
  5372. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5373. self.collection.set_all_inactive()
  5374. self.collection.set_active(
  5375. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5376. curr_sel_obj = self.collection.get_active()
  5377. # delete the possible selection box around a possible selected object
  5378. self.delete_selection_shape()
  5379. curr_sel_obj.selection_shape_drawn = False
  5380. # create the selection box around the selected object
  5381. if self.defaults['global_selection_shape'] is True:
  5382. self.draw_selection_shape(curr_sel_obj)
  5383. curr_sel_obj.selection_shape_drawn = True
  5384. self.selected_message(curr_sel_obj=curr_sel_obj)
  5385. else:
  5386. # deselect everything
  5387. self.collection.on_objects_selection(False)
  5388. # delete the possible selection box around a possible selected object
  5389. self.delete_selection_shape()
  5390. for o in self.collection.get_list():
  5391. o.selection_shape_drawn = False
  5392. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5393. # only when working on App
  5394. if self.call_source == 'app':
  5395. if self.click_noproject is False:
  5396. # if the Tool Tab is in focus don't change focus to Project Tab
  5397. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5398. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5399. else:
  5400. # restore auto open the Project Tab
  5401. self.click_noproject = False
  5402. # delete any text in the status bar, implicitly the last object name that was selected
  5403. # self.inform.emit("")
  5404. else:
  5405. self.call_source = 'app'
  5406. except Exception as e:
  5407. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5408. def selected_message(self, curr_sel_obj):
  5409. if curr_sel_obj:
  5410. if curr_sel_obj.kind == 'gerber':
  5411. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5412. color='green',
  5413. name=str(curr_sel_obj.options['name']),
  5414. tx=_("selected"))
  5415. )
  5416. elif curr_sel_obj.kind == 'excellon':
  5417. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5418. color='brown',
  5419. name=str(curr_sel_obj.options['name']),
  5420. tx=_("selected"))
  5421. )
  5422. elif curr_sel_obj.kind == 'cncjob':
  5423. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5424. color='blue',
  5425. name=str(curr_sel_obj.options['name']),
  5426. tx=_("selected"))
  5427. )
  5428. elif curr_sel_obj.kind == 'geometry':
  5429. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5430. color='red',
  5431. name=str(curr_sel_obj.options['name']),
  5432. tx=_("selected"))
  5433. )
  5434. def delete_hover_shape(self):
  5435. self.hover_shapes.clear()
  5436. self.hover_shapes.redraw()
  5437. def draw_hover_shape(self, sel_obj, color=None):
  5438. """
  5439. :param sel_obj: The object for which the hover shape must be drawn
  5440. :param color: The color of the hover shape
  5441. :return: None
  5442. """
  5443. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5444. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5445. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5446. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5447. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5448. if self.defaults['units'].upper() == 'MM':
  5449. hover_rect = hover_rect.buffer(-0.1)
  5450. hover_rect = hover_rect.buffer(0.2)
  5451. else:
  5452. hover_rect = hover_rect.buffer(-0.00393)
  5453. hover_rect = hover_rect.buffer(0.00787)
  5454. # if color:
  5455. # face = Color(color)
  5456. # face.alpha = 0.2
  5457. # outline = Color(color, alpha=0.8)
  5458. # else:
  5459. # face = Color(self.defaults['global_sel_fill'])
  5460. # face.alpha = 0.2
  5461. # outline = self.defaults['global_sel_line']
  5462. if color:
  5463. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5464. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5465. else:
  5466. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5467. outline = self.defaults['global_sel_line']
  5468. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5469. if self.is_legacy is True:
  5470. self.hover_shapes.redraw()
  5471. def delete_selection_shape(self):
  5472. self.move_tool.sel_shapes.clear()
  5473. self.move_tool.sel_shapes.redraw()
  5474. def draw_selection_shape(self, sel_obj, color=None):
  5475. """
  5476. Will draw a selection shape around the selected object.
  5477. :param sel_obj: The object for which the selection shape must be drawn
  5478. :param color: The color for the selection shape.
  5479. :return: None
  5480. """
  5481. if sel_obj is None:
  5482. return
  5483. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5484. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5485. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5486. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5487. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5488. if self.defaults['units'].upper() == 'MM':
  5489. sel_rect = sel_rect.buffer(-0.1)
  5490. sel_rect = sel_rect.buffer(0.2)
  5491. else:
  5492. sel_rect = sel_rect.buffer(-0.00393)
  5493. sel_rect = sel_rect.buffer(0.00787)
  5494. if color:
  5495. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5496. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5497. else:
  5498. if self.is_legacy is False:
  5499. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5500. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5501. else:
  5502. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5503. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5504. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5505. color=outline,
  5506. face_color=face,
  5507. update=True,
  5508. layer=0,
  5509. tolerance=None))
  5510. if self.is_legacy is True:
  5511. self.move_tool.sel_shapes.redraw()
  5512. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5513. """
  5514. Will draw a selection shape when dragging mouse on canvas.
  5515. :param old_coords: Old coordinates
  5516. :param coords: New coordinates
  5517. :param kwargs: Keyword arguments
  5518. :return:
  5519. """
  5520. if 'color' in kwargs:
  5521. color = kwargs['color']
  5522. else:
  5523. color = self.defaults['global_sel_line']
  5524. if 'face_color' in kwargs:
  5525. face_color = kwargs['face_color']
  5526. else:
  5527. face_color = self.defaults['global_sel_fill']
  5528. if 'face_alpha' in kwargs:
  5529. face_alpha = kwargs['face_alpha']
  5530. else:
  5531. face_alpha = 0.3
  5532. x0, y0 = old_coords
  5533. x1, y1 = coords
  5534. pt1 = (x0, y0)
  5535. pt2 = (x1, y0)
  5536. pt3 = (x1, y1)
  5537. pt4 = (x0, y1)
  5538. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5539. # color_t = Color(face_color)
  5540. # color_t.alpha = face_alpha
  5541. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5542. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5543. layer=0, tolerance=None)
  5544. if self.is_legacy is True:
  5545. self.move_tool.sel_shapes.redraw()
  5546. def on_file_new_click(self):
  5547. """
  5548. Callback for menu item File -> New.
  5549. Executed on clicking the Menu -> File -> New Project
  5550. :return:
  5551. """
  5552. if self.collection.get_list() and self.should_we_save:
  5553. msgbox = QtWidgets.QMessageBox()
  5554. # msgbox.setText("<B>Save changes ...</B>")
  5555. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5556. "Creating a New project will delete them.\n"
  5557. "Do you want to Save the project?"))
  5558. msgbox.setWindowTitle(_("Save changes"))
  5559. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5560. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5561. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5562. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5563. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5564. msgbox.setDefaultButton(bt_yes)
  5565. msgbox.exec_()
  5566. response = msgbox.clickedButton()
  5567. if response == bt_yes:
  5568. self.on_file_saveprojectas()
  5569. elif response == bt_cancel:
  5570. return
  5571. elif response == bt_no:
  5572. self.on_file_new()
  5573. else:
  5574. self.on_file_new()
  5575. self.inform.emit('[success] %s...' % _("New Project created"))
  5576. def on_file_new(self, cli=None):
  5577. """
  5578. Returns the application to its startup state. This method is thread-safe.
  5579. :param cli: Boolean. If True this method was run from command line
  5580. :return: None
  5581. """
  5582. self.defaults.report_usage("on_file_new")
  5583. # Remove everything from memory
  5584. App.log.debug("on_file_new()")
  5585. # close any editor that might be open
  5586. if self.call_source != 'app':
  5587. self.editor2object(cleanup=True)
  5588. # ## EDITOR section
  5589. self.geo_editor = AppGeoEditor(self)
  5590. self.exc_editor = AppExcEditor(self)
  5591. self.grb_editor = AppGerberEditor(self)
  5592. # Clear pool
  5593. self.clear_pool()
  5594. for obj in self.collection.get_list():
  5595. # delete shapes left drawn from mark shape_collections, if any
  5596. if isinstance(obj, GerberObject):
  5597. try:
  5598. obj.mark_shapes_storage.clear()
  5599. obj.mark_shapes.clear(update=True)
  5600. obj.mark_shapes.enabled = False
  5601. except AttributeError:
  5602. pass
  5603. # also delete annotation shapes, if any
  5604. elif isinstance(obj, CNCJobObject):
  5605. try:
  5606. obj.text_col.enabled = False
  5607. del obj.text_col
  5608. obj.annotation.clear(update=True)
  5609. del obj.annotation
  5610. except AttributeError:
  5611. pass
  5612. # delete the exclusion areas
  5613. self.exc_areas.clear_shapes()
  5614. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5615. self.shell.init_tcl()
  5616. # delete any selection shape on canvas
  5617. self.delete_selection_shape()
  5618. # delete all FlatCAM objects
  5619. self.collection.delete_all()
  5620. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5621. self.setup_component_editor()
  5622. # Clear project filename
  5623. self.project_filename = None
  5624. # Load the application defaults
  5625. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5626. # Re-fresh project options
  5627. self.on_options_app2project()
  5628. # Init FlatCAMTools
  5629. self.init_tools()
  5630. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5631. if cli is None:
  5632. # we need to go in reverse because once we remove a tab then the index changes
  5633. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5634. # and so on. Therefore the deletion should be done in reverse
  5635. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5636. for index in range(wdg_count, -1, -1):
  5637. try:
  5638. self.ui.plot_tab_area.closeTab(index)
  5639. except Exception as e:
  5640. log.debug("App.on_file_new() --> %s" % str(e))
  5641. # # And then add again the Plot Area
  5642. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5643. self.ui.plot_tab_area.protectTab(0)
  5644. # take the focus of the Notebook on Project Tab.
  5645. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5646. self.set_ui_title(name=_("New Project - Not saved"))
  5647. def obj_properties(self):
  5648. """
  5649. Will launch the object Properties Tool
  5650. :return:
  5651. """
  5652. self.defaults.report_usage("obj_properties()")
  5653. self.properties_tool.run(toggle=False)
  5654. def on_project_context_save(self):
  5655. """
  5656. Wrapper, will save the object function of it's type
  5657. :return:
  5658. """
  5659. sel_objects = self.collection.get_selected()
  5660. len_objects = len(sel_objects)
  5661. cnt = 0
  5662. if len_objects > 1:
  5663. for o in sel_objects:
  5664. if o.kind == 'cncjob':
  5665. cnt += 1
  5666. if len_objects == cnt:
  5667. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5668. _filter_ = self.defaults['cncjob_save_filters'] + \
  5669. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5670. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5671. try:
  5672. filename, _f = FCFileSaveDialog.get_saved_filename(
  5673. caption=_("Export Code ..."),
  5674. directory=dir_file_to_save,
  5675. ext_filter=_filter_
  5676. )
  5677. except TypeError:
  5678. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5679. ext_filter=_filter_)
  5680. filename = filename.rpartition('/')[0]
  5681. for ob in sel_objects:
  5682. ob.read_form()
  5683. fname = '%s/%s' % (filename, ob.options['name'])
  5684. ob.export_gcode_handler(fname, is_gcode=True)
  5685. return
  5686. obj = self.collection.get_active()
  5687. if type(obj) == GeometryObject:
  5688. self.on_file_exportdxf()
  5689. elif type(obj) == ExcellonObject:
  5690. self.on_file_saveexcellon()
  5691. elif type(obj) == CNCJobObject:
  5692. obj.on_exportgcode_button_click()
  5693. elif type(obj) == GerberObject:
  5694. self.on_file_savegerber()
  5695. elif type(obj) == ScriptObject:
  5696. self.on_file_savescript()
  5697. elif type(obj) == DocumentObject:
  5698. self.on_file_savedocument()
  5699. def obj_move(self):
  5700. """
  5701. Callback for the Move menu entry in various Context Menu's.
  5702. :return:
  5703. """
  5704. self.defaults.report_usage("obj_move()")
  5705. self.move_tool.run(toggle=False)
  5706. def on_fileopengerber(self, signal, name=None):
  5707. """
  5708. File menu callback for opening a Gerber.
  5709. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5710. :param name:
  5711. :return: None
  5712. """
  5713. self.defaults.report_usage("on_fileopengerber")
  5714. App.log.debug("on_fileopengerber()")
  5715. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5716. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5717. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5718. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5719. "*.outline);;" \
  5720. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5721. "*.mil);;" \
  5722. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5723. "Allegro Files (*.art);;" \
  5724. "Mentor Files (*.pho *.gdo);;" \
  5725. "All Files (*.*)"
  5726. if name is None:
  5727. try:
  5728. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5729. directory=self.get_last_folder(),
  5730. filter=_filter_,
  5731. initialFilter=self.last_op_gerber_filter)
  5732. except TypeError:
  5733. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5734. filenames = [str(filename) for filename in filenames]
  5735. self.last_op_gerber_filter = _f
  5736. else:
  5737. filenames = [name]
  5738. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5739. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5740. _("Opening Gerber file.")),
  5741. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5742. color=QtGui.QColor("gray"))
  5743. if len(filenames) == 0:
  5744. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5745. else:
  5746. for filename in filenames:
  5747. if filename != '':
  5748. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5749. def on_fileopenexcellon(self, signal, name=None):
  5750. """
  5751. File menu callback for opening an Excellon file.
  5752. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5753. :param name:
  5754. :return: None
  5755. """
  5756. self.defaults.report_usage("on_fileopenexcellon")
  5757. App.log.debug("on_fileopenexcellon()")
  5758. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5759. "All Files (*.*)"
  5760. if name is None:
  5761. try:
  5762. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5763. directory=self.get_last_folder(),
  5764. filter=_filter_,
  5765. initialFilter=self.last_op_excellon_filter)
  5766. except TypeError:
  5767. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5768. filenames = [str(filename) for filename in filenames]
  5769. self.last_op_excellon_filter = _f
  5770. else:
  5771. filenames = [str(name)]
  5772. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5773. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5774. _("Opening Excellon file.")),
  5775. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5776. color=QtGui.QColor("gray"))
  5777. if len(filenames) == 0:
  5778. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5779. else:
  5780. for filename in filenames:
  5781. if filename != '':
  5782. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5783. def on_fileopengcode(self, signal, name=None):
  5784. """
  5785. File menu call back for opening gcode.
  5786. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5787. :param name:
  5788. :return:
  5789. """
  5790. self.defaults.report_usage("on_fileopengcode")
  5791. App.log.debug("on_fileopengcode()")
  5792. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5793. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5794. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5795. "All Files (*.*)"
  5796. if name is None:
  5797. try:
  5798. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5799. directory=self.get_last_folder(),
  5800. filter=_filter_,
  5801. initialFilter=self.last_op_gcode_filter)
  5802. except TypeError:
  5803. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5804. filenames = [str(filename) for filename in filenames]
  5805. self.last_op_gcode_filter = _f
  5806. else:
  5807. filenames = [name]
  5808. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5809. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5810. _("Opening G-Code file.")),
  5811. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5812. color=QtGui.QColor("gray"))
  5813. if len(filenames) == 0:
  5814. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5815. else:
  5816. for filename in filenames:
  5817. if filename != '':
  5818. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5819. def on_file_openproject(self, signal):
  5820. """
  5821. File menu callback for opening a project.
  5822. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5823. :return: None
  5824. """
  5825. self.defaults.report_usage("on_file_openproject")
  5826. App.log.debug("on_file_openproject()")
  5827. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5828. try:
  5829. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5830. directory=self.get_last_folder(), filter=_filter_)
  5831. except TypeError:
  5832. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5833. # The Qt methods above will return a QString which can cause problems later.
  5834. # So far json.dump() will fail to serialize it.
  5835. # TODO: Improve the serialization methods and remove this fix.
  5836. filename = str(filename)
  5837. if filename == "":
  5838. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5839. else:
  5840. # self.worker_task.emit({'fcn': self.open_project,
  5841. # 'params': [filename]})
  5842. # The above was failing because open_project() is not
  5843. # thread safe. The new_project()
  5844. self.open_project(filename)
  5845. def on_fileopenhpgl2(self, signal, name=None):
  5846. """
  5847. File menu callback for opening a HPGL2.
  5848. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5849. :param name:
  5850. :return: None
  5851. """
  5852. self.defaults.report_usage("on_fileopenhpgl2")
  5853. App.log.debug("on_fileopenhpgl2()")
  5854. _filter_ = "HPGL2 Files (*.plt);;" \
  5855. "All Files (*.*)"
  5856. if name is None:
  5857. try:
  5858. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5859. directory=self.get_last_folder(),
  5860. filter=_filter_)
  5861. except TypeError:
  5862. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5863. filenames = [str(filename) for filename in filenames]
  5864. else:
  5865. filenames = [name]
  5866. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5867. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5868. _("Opening HPGL2 file.")),
  5869. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5870. color=QtGui.QColor("gray"))
  5871. if len(filenames) == 0:
  5872. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5873. else:
  5874. for filename in filenames:
  5875. if filename != '':
  5876. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5877. def on_file_openconfig(self, signal):
  5878. """
  5879. File menu callback for opening a config file.
  5880. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5881. :return: None
  5882. """
  5883. self.defaults.report_usage("on_file_openconfig")
  5884. App.log.debug("on_file_openconfig()")
  5885. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5886. try:
  5887. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5888. directory=self.data_path, filter=_filter_)
  5889. except TypeError:
  5890. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5891. filter=_filter_)
  5892. if filename == "":
  5893. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5894. else:
  5895. self.open_config_file(filename)
  5896. def on_file_exportsvg(self):
  5897. """
  5898. Callback for menu item File->Export SVG.
  5899. :return: None
  5900. """
  5901. self.defaults.report_usage("on_file_exportsvg")
  5902. App.log.debug("on_file_exportsvg()")
  5903. obj = self.collection.get_active()
  5904. if obj is None:
  5905. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5906. msg = _("Please Select a Geometry object to export")
  5907. msgbox = QtWidgets.QMessageBox()
  5908. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5909. msgbox.setInformativeText(msg)
  5910. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5911. msgbox.setDefaultButton(bt_ok)
  5912. msgbox.exec_()
  5913. return
  5914. # Check for more compatible types and add as required
  5915. if (not isinstance(obj, GeometryObject)
  5916. and not isinstance(obj, GerberObject)
  5917. and not isinstance(obj, CNCJobObject)
  5918. and not isinstance(obj, ExcellonObject)):
  5919. msg = '[ERROR_NOTCL] %s' % \
  5920. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5921. msgbox = QtWidgets.QMessageBox()
  5922. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5923. msgbox.setInformativeText(msg)
  5924. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5925. msgbox.setDefaultButton(bt_ok)
  5926. msgbox.exec_()
  5927. return
  5928. name = obj.options["name"]
  5929. _filter = "SVG File (*.svg);;All Files (*.*)"
  5930. try:
  5931. filename, _f = FCFileSaveDialog.get_saved_filename(
  5932. caption=_("Export SVG"),
  5933. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5934. ext_filter=_filter)
  5935. except TypeError:
  5936. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5937. filename = str(filename)
  5938. if filename == "":
  5939. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5940. return
  5941. else:
  5942. self.export_svg(name, filename)
  5943. if self.defaults["global_open_style"] is False:
  5944. self.file_opened.emit("SVG", filename)
  5945. self.file_saved.emit("SVG", filename)
  5946. def on_file_exportpng(self):
  5947. self.defaults.report_usage("on_file_exportpng")
  5948. App.log.debug("on_file_exportpng()")
  5949. self.date = str(datetime.today()).rpartition('.')[0]
  5950. self.date = ''.join(c for c in self.date if c not in ':-')
  5951. self.date = self.date.replace(' ', '_')
  5952. data = None
  5953. if self.is_legacy is False:
  5954. image = _screenshot(alpha=False)
  5955. data = np.asarray(image)
  5956. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5957. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5958. return
  5959. filter_ = "PNG File (*.png);;All Files (*.*)"
  5960. try:
  5961. filename, _f = FCFileSaveDialog.get_saved_filename(
  5962. caption=_("Export PNG Image"),
  5963. directory=self.get_last_save_folder() + '/png_' + self.date,
  5964. ext_filter=filter_)
  5965. except TypeError:
  5966. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5967. filename = str(filename)
  5968. if filename == "":
  5969. self.inform.emit(_("Cancelled."))
  5970. return
  5971. else:
  5972. if self.is_legacy is False:
  5973. write_png(filename, data)
  5974. else:
  5975. self.plotcanvas.figure.savefig(filename)
  5976. if self.defaults["global_open_style"] is False:
  5977. self.file_opened.emit("png", filename)
  5978. self.file_saved.emit("png", filename)
  5979. def on_file_savegerber(self):
  5980. """
  5981. Callback for menu item in Project context menu.
  5982. :return: None
  5983. """
  5984. self.defaults.report_usage("on_file_savegerber")
  5985. App.log.debug("on_file_savegerber()")
  5986. obj = self.collection.get_active()
  5987. if obj is None:
  5988. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5989. return
  5990. # Check for more compatible types and add as required
  5991. if not isinstance(obj, GerberObject):
  5992. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5993. return
  5994. name = self.collection.get_active().options["name"]
  5995. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5996. try:
  5997. filename, _f = FCFileSaveDialog.get_saved_filename(
  5998. caption="Save Gerber source file",
  5999. directory=self.get_last_save_folder() + '/' + name,
  6000. ext_filter=_filter)
  6001. except TypeError:
  6002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6003. filename = str(filename)
  6004. if filename == "":
  6005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6006. return
  6007. else:
  6008. self.save_source_file(name, filename)
  6009. if self.defaults["global_open_style"] is False:
  6010. self.file_opened.emit("Gerber", filename)
  6011. self.file_saved.emit("Gerber", filename)
  6012. def on_file_savescript(self):
  6013. """
  6014. Callback for menu item in Project context menu.
  6015. :return: None
  6016. """
  6017. self.defaults.report_usage("on_file_savescript")
  6018. App.log.debug("on_file_savescript()")
  6019. obj = self.collection.get_active()
  6020. if obj is None:
  6021. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6022. return
  6023. # Check for more compatible types and add as required
  6024. if not isinstance(obj, ScriptObject):
  6025. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6026. return
  6027. name = self.collection.get_active().options["name"]
  6028. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6029. try:
  6030. filename, _f = FCFileSaveDialog.get_saved_filename(
  6031. caption="Save Script source file",
  6032. directory=self.get_last_save_folder() + '/' + name,
  6033. ext_filter=_filter)
  6034. except TypeError:
  6035. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6036. filename = str(filename)
  6037. if filename == "":
  6038. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6039. return
  6040. else:
  6041. self.save_source_file(name, filename)
  6042. if self.defaults["global_open_style"] is False:
  6043. self.file_opened.emit("Script", filename)
  6044. self.file_saved.emit("Script", filename)
  6045. def on_file_savedocument(self):
  6046. """
  6047. Callback for menu item in Project context menu.
  6048. :return: None
  6049. """
  6050. self.defaults.report_usage("on_file_savedocument")
  6051. App.log.debug("on_file_savedocument()")
  6052. obj = self.collection.get_active()
  6053. if obj is None:
  6054. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6055. return
  6056. # Check for more compatible types and add as required
  6057. if not isinstance(obj, ScriptObject):
  6058. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6059. return
  6060. name = self.collection.get_active().options["name"]
  6061. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6062. try:
  6063. filename, _f = FCFileSaveDialog.get_saved_filename(
  6064. caption="Save Document source file",
  6065. directory=self.get_last_save_folder() + '/' + name,
  6066. ext_filter=_filter)
  6067. except TypeError:
  6068. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6069. ext_filter=_filter)
  6070. filename = str(filename)
  6071. if filename == "":
  6072. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6073. return
  6074. else:
  6075. self.save_source_file(name, filename)
  6076. if self.defaults["global_open_style"] is False:
  6077. self.file_opened.emit("Document", filename)
  6078. self.file_saved.emit("Document", filename)
  6079. def on_file_saveexcellon(self):
  6080. """
  6081. Callback for menu item in project context menu.
  6082. :return: None
  6083. """
  6084. self.defaults.report_usage("on_file_saveexcellon")
  6085. App.log.debug("on_file_saveexcellon()")
  6086. obj = self.collection.get_active()
  6087. if obj is None:
  6088. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6089. return
  6090. # Check for more compatible types and add as required
  6091. if not isinstance(obj, ExcellonObject):
  6092. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6093. return
  6094. name = self.collection.get_active().options["name"]
  6095. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6096. try:
  6097. filename, _f = FCFileSaveDialog.get_saved_filename(
  6098. caption=_("Save Excellon source file"),
  6099. directory=self.get_last_save_folder() + '/' + name,
  6100. ext_filter=_filter)
  6101. except TypeError:
  6102. filename, _f = FCFileSaveDialog.get_saved_filename(
  6103. caption=_("Save Excellon source file"), ext_filter=_filter)
  6104. filename = str(filename)
  6105. if filename == "":
  6106. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6107. return
  6108. else:
  6109. self.save_source_file(name, filename)
  6110. if self.defaults["global_open_style"] is False:
  6111. self.file_opened.emit("Excellon", filename)
  6112. self.file_saved.emit("Excellon", filename)
  6113. def on_file_exportexcellon(self):
  6114. """
  6115. Callback for menu item File->Export->Excellon.
  6116. :return: None
  6117. """
  6118. self.defaults.report_usage("on_file_exportexcellon")
  6119. App.log.debug("on_file_exportexcellon()")
  6120. obj = self.collection.get_active()
  6121. if obj is None:
  6122. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6123. return
  6124. # Check for more compatible types and add as required
  6125. if not isinstance(obj, ExcellonObject):
  6126. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6127. return
  6128. name = self.collection.get_active().options["name"]
  6129. _filter = self.defaults["excellon_save_filters"]
  6130. try:
  6131. filename, _f = FCFileSaveDialog.get_saved_filename(
  6132. caption=_("Export Excellon"),
  6133. directory=self.get_last_save_folder() + '/' + name,
  6134. ext_filter=_filter)
  6135. except TypeError:
  6136. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6137. filename = str(filename)
  6138. if filename == "":
  6139. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6140. return
  6141. else:
  6142. used_extension = filename.rpartition('.')[2]
  6143. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6144. self.export_excellon(name, filename)
  6145. if self.defaults["global_open_style"] is False:
  6146. self.file_opened.emit("Excellon", filename)
  6147. self.file_saved.emit("Excellon", filename)
  6148. def on_file_exportgerber(self):
  6149. """
  6150. Callback for menu item File->Export->Gerber.
  6151. :return: None
  6152. """
  6153. self.defaults.report_usage("on_file_exportgerber")
  6154. App.log.debug("on_file_exportgerber()")
  6155. obj = self.collection.get_active()
  6156. if obj is None:
  6157. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6158. return
  6159. # Check for more compatible types and add as required
  6160. if not isinstance(obj, GerberObject):
  6161. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6162. return
  6163. name = self.collection.get_active().options["name"]
  6164. _filter_ = self.defaults['gerber_save_filters']
  6165. try:
  6166. filename, _f = FCFileSaveDialog.get_saved_filename(
  6167. caption=_("Export Gerber"),
  6168. directory=self.get_last_save_folder() + '/' + name,
  6169. ext_filter=_filter_)
  6170. except TypeError:
  6171. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6172. filename = str(filename)
  6173. if filename == "":
  6174. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6175. return
  6176. else:
  6177. used_extension = filename.rpartition('.')[2]
  6178. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6179. self.export_gerber(name, filename)
  6180. if self.defaults["global_open_style"] is False:
  6181. self.file_opened.emit("Gerber", filename)
  6182. self.file_saved.emit("Gerber", filename)
  6183. def on_file_exportdxf(self):
  6184. """
  6185. Callback for menu item File->Export DXF.
  6186. :return: None
  6187. """
  6188. self.defaults.report_usage("on_file_exportdxf")
  6189. App.log.debug("on_file_exportdxf()")
  6190. obj = self.collection.get_active()
  6191. if obj is None:
  6192. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6193. msg = _("Please Select a Geometry object to export")
  6194. msgbox = QtWidgets.QMessageBox()
  6195. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6196. msgbox.setInformativeText(msg)
  6197. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6198. msgbox.setDefaultButton(bt_ok)
  6199. msgbox.exec_()
  6200. return
  6201. # Check for more compatible types and add as required
  6202. if not isinstance(obj, GeometryObject):
  6203. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6204. msgbox = QtWidgets.QMessageBox()
  6205. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6206. msgbox.setInformativeText(msg)
  6207. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6208. msgbox.setDefaultButton(bt_ok)
  6209. msgbox.exec_()
  6210. return
  6211. name = self.collection.get_active().options["name"]
  6212. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6213. try:
  6214. filename, _f = FCFileSaveDialog.get_saved_filename(
  6215. caption=_("Export DXF"),
  6216. directory=self.get_last_save_folder() + '/' + name,
  6217. ext_filter=_filter_)
  6218. except TypeError:
  6219. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6220. filename = str(filename)
  6221. if filename == "":
  6222. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6223. return
  6224. else:
  6225. self.export_dxf(name, filename)
  6226. if self.defaults["global_open_style"] is False:
  6227. self.file_opened.emit("DXF", filename)
  6228. self.file_saved.emit("DXF", filename)
  6229. def on_file_importsvg(self, type_of_obj):
  6230. """
  6231. Callback for menu item File->Import SVG.
  6232. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6233. :type type_of_obj: str
  6234. :return: None
  6235. """
  6236. self.defaults.report_usage("on_file_importsvg")
  6237. App.log.debug("on_file_importsvg()")
  6238. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6239. try:
  6240. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6241. directory=self.get_last_folder(), filter=_filter_)
  6242. except TypeError:
  6243. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6244. filter=_filter_)
  6245. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6246. type_of_obj = "geometry"
  6247. filenames = [str(filename) for filename in filenames]
  6248. if len(filenames) == 0:
  6249. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6250. else:
  6251. for filename in filenames:
  6252. if filename != '':
  6253. self.worker_task.emit({'fcn': self.import_svg,
  6254. 'params': [filename, type_of_obj]})
  6255. def on_file_importdxf(self, type_of_obj):
  6256. """
  6257. Callback for menu item File->Import DXF.
  6258. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6259. :type type_of_obj: str
  6260. :return: None
  6261. """
  6262. self.defaults.report_usage("on_file_importdxf")
  6263. App.log.debug("on_file_importdxf()")
  6264. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6265. try:
  6266. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6267. directory=self.get_last_folder(),
  6268. filter=_filter_)
  6269. except TypeError:
  6270. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6271. filter=_filter_)
  6272. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6273. type_of_obj = "geometry"
  6274. filenames = [str(filename) for filename in filenames]
  6275. if len(filenames) == 0:
  6276. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6277. else:
  6278. for filename in filenames:
  6279. if filename != '':
  6280. self.worker_task.emit({'fcn': self.import_dxf,
  6281. 'params': [filename, type_of_obj]})
  6282. # ###############################################################################################################
  6283. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6284. # ###############################################################################################################
  6285. def init_code_editor(self, name):
  6286. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6287. # add the tab if it was closed
  6288. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6289. self.text_editor_tab.setObjectName('text_editor_tab')
  6290. # delete the absolute and relative position and messages in the infobar
  6291. # self.ui.position_label.setText("")
  6292. # self.ui.rel_position_label.setText("")
  6293. # hide coordinates toolbars in the infobar while in DB
  6294. self.ui.coords_toolbar.hide()
  6295. self.ui.delta_coords_toolbar.hide()
  6296. self.toggle_codeeditor = True
  6297. self.text_editor_tab.code_editor.completer_enable = False
  6298. self.text_editor_tab.buttonRun.hide()
  6299. # make sure to keep a reference to the code editor
  6300. self.reference_code_editor = self.text_editor_tab.code_editor
  6301. # Switch plot_area to CNCJob tab
  6302. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6303. def on_view_source(self):
  6304. """
  6305. Called when the user wants to see the source file of the selected object
  6306. :return:
  6307. """
  6308. try:
  6309. obj = self.collection.get_active()
  6310. except Exception as e:
  6311. log.debug("App.on_view_source() --> %s" % str(e))
  6312. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6313. return 'fail'
  6314. if obj is None:
  6315. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6316. return 'fail'
  6317. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6318. self.proc_container.view.set_busy(_("Loading..."))
  6319. flt = "All Files (*.*)"
  6320. if obj.kind == 'gerber':
  6321. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6322. elif obj.kind == 'excellon':
  6323. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6324. elif obj.kind == 'cncjob':
  6325. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6326. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6327. # add the tab if it was closed
  6328. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6329. self.source_editor_tab.setObjectName('source_editor_tab')
  6330. # delete the absolute and relative position and messages in the infobar
  6331. # self.ui.position_label.setText("")
  6332. # self.ui.rel_position_label.setText("")
  6333. # hide coordinates toolbars in the infobar while in DB
  6334. self.ui.coords_toolbar.hide()
  6335. self.ui.delta_coords_toolbar.hide()
  6336. self.source_editor_tab.code_editor.completer_enable = False
  6337. self.source_editor_tab.buttonRun.hide()
  6338. # Switch plot_area to CNCJob tab
  6339. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6340. try:
  6341. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6342. except TypeError:
  6343. pass
  6344. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6345. try:
  6346. self.source_editor_tab.buttonSave.clicked.disconnect()
  6347. except TypeError:
  6348. pass
  6349. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6350. # then append the text from GCode to the text editor
  6351. if obj.kind == 'cncjob':
  6352. try:
  6353. file = obj.export_gcode(
  6354. preamble=self.defaults["cncjob_prepend"],
  6355. postamble=self.defaults["cncjob_append"],
  6356. to_file=True)
  6357. if file == 'fail':
  6358. return 'fail'
  6359. except AttributeError:
  6360. self.inform.emit('[WARNING_NOTCL] %s' %
  6361. _("There is no selected object for which to see it's source file code."))
  6362. return 'fail'
  6363. else:
  6364. try:
  6365. file = StringIO(obj.source_file)
  6366. except (AttributeError, TypeError):
  6367. self.inform.emit('[WARNING_NOTCL] %s' %
  6368. _("There is no selected object for which to see it's source file code."))
  6369. return 'fail'
  6370. self.source_editor_tab.t_frame.hide()
  6371. try:
  6372. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  6373. except Exception as e:
  6374. log.debug('App.on_view_source() -->%s' % str(e))
  6375. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6376. return
  6377. self.source_editor_tab.t_frame.show()
  6378. self.proc_container.view.set_idle()
  6379. # self.ui.show()
  6380. def on_toggle_code_editor(self):
  6381. self.defaults.report_usage("on_toggle_code_editor()")
  6382. if self.toggle_codeeditor is False:
  6383. self.init_code_editor(name=_("Code Editor"))
  6384. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6385. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6386. self.text_editor_tab.buttonSave.clicked.disconnect()
  6387. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6388. else:
  6389. for idx in range(self.ui.plot_tab_area.count()):
  6390. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6391. self.ui.plot_tab_area.closeTab(idx)
  6392. break
  6393. self.toggle_codeeditor = False
  6394. def on_code_editor_close(self):
  6395. self.toggle_codeeditor = False
  6396. def goto_text_line(self):
  6397. """
  6398. Will scroll a text to the specified text line.
  6399. :return: None
  6400. """
  6401. dia_box = Dialog_box(title=_("Go to Line ..."),
  6402. label=_("Line:"),
  6403. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6404. initial_text='')
  6405. try:
  6406. line = int(dia_box.location) - 1
  6407. except (ValueError, TypeError):
  6408. line = 0
  6409. if dia_box.ok:
  6410. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6411. # at the top of the window
  6412. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6413. # get the document() of the AppTextEditor
  6414. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6415. # create a Text Cursor based on the searched line
  6416. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6417. # set cursor of the code editor with the cursor at the searcehd line
  6418. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6419. def on_filenewscript(self, silent=False):
  6420. """
  6421. Will create a new script file and open it in the Code Editor
  6422. :param silent: if True will not display status messages
  6423. :return: None
  6424. """
  6425. if silent is False:
  6426. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6427. # delete the absolute and relative position and messages in the infobar
  6428. # self.ui.position_label.setText("")
  6429. # self.ui.rel_position_label.setText("")
  6430. # hide coordinates toolbars in the infobar while in DB
  6431. self.ui.coords_toolbar.hide()
  6432. self.ui.delta_coords_toolbar.hide()
  6433. self.app_obj.new_script_object()
  6434. # script_text = script_obj.source_file
  6435. #
  6436. # self.proc_container.view.set_busy(_("Loading..."))
  6437. # script_obj.script_editor_tab.t_frame.hide()
  6438. #
  6439. # script_obj.script_editor_tab.t_frame.show()
  6440. # self.proc_container.view.set_idle()
  6441. def on_fileopenscript(self, name=None, silent=False):
  6442. """
  6443. Will open a Tcl script file into the Code Editor
  6444. :param silent: if True will not display status messages
  6445. :param name: name of a Tcl script file to open
  6446. :return: None
  6447. """
  6448. self.defaults.report_usage("on_fileopenscript")
  6449. App.log.debug("on_fileopenscript()")
  6450. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6451. "All Files (*.*)"
  6452. if name:
  6453. filenames = [name]
  6454. else:
  6455. try:
  6456. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6457. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6458. except TypeError:
  6459. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6460. if len(filenames) == 0:
  6461. if silent is False:
  6462. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6463. else:
  6464. for filename in filenames:
  6465. if filename != '':
  6466. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6467. def on_fileopenscript_example(self, name=None, silent=False):
  6468. """
  6469. Will open a Tcl script file into the Code Editor
  6470. :param silent: if True will not display status messages
  6471. :param name: name of a Tcl script file to open
  6472. :return:
  6473. """
  6474. self.defaults.report_usage("on_fileopenscript_example")
  6475. log.debug("on_fileopenscript_example()")
  6476. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6477. "All Files (*.*)"
  6478. # test if the app was frozen and choose the path for the configuration file
  6479. if getattr(sys, "frozen", False) is True:
  6480. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6481. else:
  6482. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6483. if name:
  6484. filenames = [name]
  6485. else:
  6486. try:
  6487. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6488. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6489. except TypeError:
  6490. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6491. if len(filenames) == 0:
  6492. if silent is False:
  6493. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6494. else:
  6495. for filename in filenames:
  6496. if filename != '':
  6497. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6498. def on_filerunscript(self, name=None, silent=False):
  6499. """
  6500. File menu callback for loading and running a TCL script.
  6501. :param silent: if True will not display status messages
  6502. :param name: name of a Tcl script file to be run by FlatCAM
  6503. :return: None
  6504. """
  6505. self.defaults.report_usage("on_filerunscript")
  6506. App.log.debug("on_file_runscript()")
  6507. if name:
  6508. filename = name
  6509. if self.cmd_line_headless != 1:
  6510. self.splash.showMessage('%s: %ssec\n%s' %
  6511. (_("Canvas initialization started.\n"
  6512. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6513. _("Executing ScriptObject file.")
  6514. ),
  6515. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6516. color=QtGui.QColor("gray"))
  6517. else:
  6518. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6519. "All Files (*.*)"
  6520. try:
  6521. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6522. directory=self.get_last_folder(), filter=_filter_)
  6523. except TypeError:
  6524. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6525. # The Qt methods above will return a QString which can cause problems later.
  6526. # So far json.dump() will fail to serialize it.
  6527. filename = str(filename)
  6528. if filename == "":
  6529. if silent is False:
  6530. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6531. else:
  6532. if self.cmd_line_headless != 1:
  6533. if self.ui.shell_dock.isHidden():
  6534. self.ui.shell_dock.show()
  6535. try:
  6536. with open(filename, "r") as tcl_script:
  6537. cmd_line_shellfile_content = tcl_script.read()
  6538. if self.cmd_line_headless != 1:
  6539. self.shell.exec_command(cmd_line_shellfile_content)
  6540. else:
  6541. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6542. if silent is False:
  6543. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6544. except Exception as e:
  6545. log.debug("App.on_filerunscript() -> %s" % str(e))
  6546. sys.exit(2)
  6547. def on_file_saveproject(self, silent=False):
  6548. """
  6549. Callback for menu item File->Save Project. Saves the project to
  6550. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6551. if set to None. The project is saved by calling ``self.save_project()``.
  6552. :param silent: if True will not display status messages
  6553. :return: None
  6554. """
  6555. self.defaults.report_usage("on_file_saveproject")
  6556. if self.project_filename is None:
  6557. self.on_file_saveprojectas()
  6558. else:
  6559. self.worker_task.emit({'fcn': self.save_project,
  6560. 'params': [self.project_filename, silent]})
  6561. if self.defaults["global_open_style"] is False:
  6562. self.file_opened.emit("project", self.project_filename)
  6563. self.file_saved.emit("project", self.project_filename)
  6564. self.set_ui_title(name=self.project_filename)
  6565. self.should_we_save = False
  6566. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6567. """
  6568. Callback for menu item File->Save Project As... Opens a file
  6569. chooser and saves the project to the given file via
  6570. ``self.save_project()``.
  6571. :param make_copy if to be create a copy of the project; boolean
  6572. :param use_thread: if to be run in a separate thread; boolean
  6573. :param quit_action: if to be followed by quiting the application; boolean
  6574. :return: None
  6575. """
  6576. self.defaults.report_usage("on_file_saveprojectas")
  6577. self.date = str(datetime.today()).rpartition('.')[0]
  6578. self.date = ''.join(c for c in self.date if c not in ':-')
  6579. self.date = self.date.replace(' ', '_')
  6580. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6581. try:
  6582. filename, _f = FCFileSaveDialog.get_saved_filename(
  6583. caption=_("Save Project As ..."),
  6584. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6585. proj=_("Project")),
  6586. ext_filter=filter_
  6587. )
  6588. except TypeError:
  6589. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6590. filename = str(filename)
  6591. if filename == '':
  6592. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6593. return
  6594. if use_thread is True:
  6595. self.worker_task.emit({'fcn': self.save_project,
  6596. 'params': [filename, quit_action]})
  6597. else:
  6598. self.save_project(filename, quit_action)
  6599. # self.save_project(filename)
  6600. if self.defaults["global_open_style"] is False:
  6601. self.file_opened.emit("project", filename)
  6602. self.file_saved.emit("project", filename)
  6603. if not make_copy:
  6604. self.project_filename = filename
  6605. self.set_ui_title(name=self.project_filename)
  6606. self.should_we_save = False
  6607. def on_file_save_objects_pdf(self, use_thread=True):
  6608. self.date = str(datetime.today()).rpartition('.')[0]
  6609. self.date = ''.join(c for c in self.date if c not in ':-')
  6610. self.date = self.date.replace(' ', '_')
  6611. try:
  6612. obj_selection = self.collection.get_selected()
  6613. if len(obj_selection) == 1:
  6614. obj_name = str(obj_selection[0].options['name'])
  6615. else:
  6616. obj_name = _("FlatCAM objects print")
  6617. except AttributeError as err:
  6618. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6619. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6620. return
  6621. if not obj_selection:
  6622. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6623. return
  6624. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6625. try:
  6626. filename, _f = FCFileSaveDialog.get_saved_filename(
  6627. caption=_("Save Object as PDF ..."),
  6628. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6629. obj_name=obj_name,
  6630. date=self.date),
  6631. ext_filter=filter_
  6632. )
  6633. except TypeError:
  6634. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6635. filename = str(filename)
  6636. if filename == '':
  6637. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6638. return
  6639. if use_thread is True:
  6640. self.proc_container.new(_("Printing PDF ... Please wait."))
  6641. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6642. else:
  6643. self.save_pdf(filename, obj_selection)
  6644. # self.save_project(filename)
  6645. if self.defaults["global_open_style"] is False:
  6646. self.file_opened.emit("pdf", filename)
  6647. self.file_saved.emit("pdf", filename)
  6648. def save_pdf(self, file_name, obj_selection):
  6649. p_size = self.defaults['global_workspaceT']
  6650. orientation = self.defaults['global_workspace_orientation']
  6651. color = 'black'
  6652. transparency_level = 1.0
  6653. self.pagesize = {}
  6654. self.pagesize.update(
  6655. {
  6656. 'Bounds': None,
  6657. 'A0': (841 * mm, 1189 * mm),
  6658. 'A1': (594 * mm, 841 * mm),
  6659. 'A2': (420 * mm, 594 * mm),
  6660. 'A3': (297 * mm, 420 * mm),
  6661. 'A4': (210 * mm, 297 * mm),
  6662. 'A5': (148 * mm, 210 * mm),
  6663. 'A6': (105 * mm, 148 * mm),
  6664. 'A7': (74 * mm, 105 * mm),
  6665. 'A8': (52 * mm, 74 * mm),
  6666. 'A9': (37 * mm, 52 * mm),
  6667. 'A10': (26 * mm, 37 * mm),
  6668. 'B0': (1000 * mm, 1414 * mm),
  6669. 'B1': (707 * mm, 1000 * mm),
  6670. 'B2': (500 * mm, 707 * mm),
  6671. 'B3': (353 * mm, 500 * mm),
  6672. 'B4': (250 * mm, 353 * mm),
  6673. 'B5': (176 * mm, 250 * mm),
  6674. 'B6': (125 * mm, 176 * mm),
  6675. 'B7': (88 * mm, 125 * mm),
  6676. 'B8': (62 * mm, 88 * mm),
  6677. 'B9': (44 * mm, 62 * mm),
  6678. 'B10': (31 * mm, 44 * mm),
  6679. 'C0': (917 * mm, 1297 * mm),
  6680. 'C1': (648 * mm, 917 * mm),
  6681. 'C2': (458 * mm, 648 * mm),
  6682. 'C3': (324 * mm, 458 * mm),
  6683. 'C4': (229 * mm, 324 * mm),
  6684. 'C5': (162 * mm, 229 * mm),
  6685. 'C6': (114 * mm, 162 * mm),
  6686. 'C7': (81 * mm, 114 * mm),
  6687. 'C8': (57 * mm, 81 * mm),
  6688. 'C9': (40 * mm, 57 * mm),
  6689. 'C10': (28 * mm, 40 * mm),
  6690. # American paper sizes
  6691. 'LETTER': (8.5 * inch, 11 * inch),
  6692. 'LEGAL': (8.5 * inch, 14 * inch),
  6693. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6694. # From https://en.wikipedia.org/wiki/Paper_size
  6695. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6696. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6697. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6698. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6699. 'LEDGER': (17 * inch, 11 * inch),
  6700. }
  6701. )
  6702. exported_svg = []
  6703. for obj in obj_selection:
  6704. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6705. scale_factor_x=None, scale_factor_y=None,
  6706. skew_factor_x=None, skew_factor_y=None,
  6707. mirror=None)
  6708. if obj.kind.lower() == 'gerber':
  6709. # color = self.defaults["gerber_plot_fill"][:-2]
  6710. color = obj.fill_color[:-2]
  6711. elif obj.kind.lower() == 'excellon':
  6712. color = '#C40000'
  6713. elif obj.kind.lower() == 'geometry':
  6714. color = self.defaults["global_draw_color"]
  6715. # Change the attributes of the exported SVG
  6716. # We don't need stroke-width
  6717. # We set opacity to maximum
  6718. # We set the colour to WHITE
  6719. root = ET.fromstring(svg_obj)
  6720. for child in root:
  6721. child.set('fill', str(color))
  6722. child.set('opacity', str(transparency_level))
  6723. child.set('stroke', str(color))
  6724. exported_svg.append(ET.tostring(root))
  6725. xmin = Inf
  6726. ymin = Inf
  6727. xmax = -Inf
  6728. ymax = -Inf
  6729. for obj in obj_selection:
  6730. try:
  6731. gxmin, gymin, gxmax, gymax = obj.bounds()
  6732. xmin = min([xmin, gxmin])
  6733. ymin = min([ymin, gymin])
  6734. xmax = max([xmax, gxmax])
  6735. ymax = max([ymax, gymax])
  6736. except Exception as e:
  6737. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6738. # Determine bounding area for svg export
  6739. bounds = [xmin, ymin, xmax, ymax]
  6740. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6741. # This contain the measure units
  6742. uom = obj_selection[0].units.lower()
  6743. # Define a boundary around SVG of about 1.0mm (~39mils)
  6744. if uom in "mm":
  6745. boundary = 1.0
  6746. else:
  6747. boundary = 0.0393701
  6748. # Convert everything to strings for use in the xml doc
  6749. svgwidth = str(size[0] + (2 * boundary))
  6750. svgheight = str(size[1] + (2 * boundary))
  6751. minx = str(bounds[0] - boundary)
  6752. miny = str(bounds[1] + boundary + size[1])
  6753. # Add a SVG Header and footer to the svg output from shapely
  6754. # The transform flips the Y Axis so that everything renders
  6755. # properly within svg apps such as inkscape
  6756. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6757. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6758. svg_header += 'width="' + svgwidth + uom + '" '
  6759. svg_header += 'height="' + svgheight + uom + '" '
  6760. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6761. svg_header += '>'
  6762. svg_header += '<g transform="scale(1,-1)">'
  6763. svg_footer = '</g> </svg>'
  6764. svg_elem = str(svg_header)
  6765. for svg_item in exported_svg:
  6766. svg_elem += str(svg_item)
  6767. svg_elem += str(svg_footer)
  6768. # Parse the xml through a xml parser just to add line feeds
  6769. # and to make it look more pretty for the output
  6770. doc = parse_xml_string(svg_elem)
  6771. doc_final = doc.toprettyxml()
  6772. try:
  6773. if self.defaults['units'].upper() == 'IN':
  6774. unit = inch
  6775. else:
  6776. unit = mm
  6777. doc_final = StringIO(doc_final)
  6778. drawing = svg2rlg(doc_final)
  6779. if p_size == 'Bounds':
  6780. renderPDF.drawToFile(drawing, file_name)
  6781. else:
  6782. if orientation == 'p':
  6783. page_size = portrait(self.pagesize[p_size])
  6784. else:
  6785. page_size = landscape(self.pagesize[p_size])
  6786. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6787. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6788. renderPDF.draw(drawing, my_canvas, 0, 0)
  6789. my_canvas.save()
  6790. except Exception as e:
  6791. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6792. return 'fail'
  6793. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6794. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6795. """
  6796. Exports a Geometry Object to an SVG file.
  6797. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6798. :param filename: Path to the SVG file to save to.
  6799. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6800. :return:
  6801. """
  6802. self.defaults.report_usage("export_svg()")
  6803. if filename is None:
  6804. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6805. is not None else self.defaults["global_last_folder"]
  6806. self.log.debug("export_svg()")
  6807. try:
  6808. obj = self.collection.get_by_name(str(obj_name))
  6809. except Exception:
  6810. # TODO: The return behavior has not been established... should raise exception?
  6811. return "Could not retrieve object: %s" % obj_name
  6812. with self.proc_container.new(_("Exporting SVG")) as proc:
  6813. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6814. # Determine bounding area for svg export
  6815. bounds = obj.bounds()
  6816. size = obj.size()
  6817. # Convert everything to strings for use in the xml doc
  6818. svgwidth = str(size[0])
  6819. svgheight = str(size[1])
  6820. minx = str(bounds[0])
  6821. miny = str(bounds[1] - size[1])
  6822. uom = obj.units.lower()
  6823. # Add a SVG Header and footer to the svg output from shapely
  6824. # The transform flips the Y Axis so that everything renders
  6825. # properly within svg apps such as inkscape
  6826. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6827. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6828. svg_header += 'width="' + svgwidth + uom + '" '
  6829. svg_header += 'height="' + svgheight + uom + '" '
  6830. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6831. svg_header += '<g transform="scale(1,-1)">'
  6832. svg_footer = '</g> </svg>'
  6833. svg_elem = svg_header + exported_svg + svg_footer
  6834. # Parse the xml through a xml parser just to add line feeds
  6835. # and to make it look more pretty for the output
  6836. svgcode = parse_xml_string(svg_elem)
  6837. svgcode = svgcode.toprettyxml()
  6838. try:
  6839. with open(filename, 'w') as fp:
  6840. fp.write(svgcode)
  6841. except PermissionError:
  6842. self.inform.emit('[WARNING] %s' %
  6843. _("Permission denied, saving not possible.\n"
  6844. "Most likely another app is holding the file open and not accessible."))
  6845. return 'fail'
  6846. if self.defaults["global_open_style"] is False:
  6847. self.file_opened.emit("SVG", filename)
  6848. self.file_saved.emit("SVG", filename)
  6849. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6850. def save_source_file(self, obj_name, filename, use_thread=True):
  6851. """
  6852. Exports a FlatCAM Object to an Gerber/Excellon file.
  6853. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6854. :param filename: Path to the Gerber file to save to.
  6855. :param use_thread: if to be run in a separate thread
  6856. :return:
  6857. """
  6858. self.defaults.report_usage("save source file()")
  6859. if filename is None:
  6860. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6861. is not None else self.defaults["global_last_folder"]
  6862. self.log.debug("save source file()")
  6863. obj = self.collection.get_by_name(obj_name)
  6864. file_string = StringIO(obj.source_file)
  6865. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6866. if file_string.getvalue() == '':
  6867. self.inform.emit('[ERROR_NOTCL] %s' %
  6868. _("Save cancelled because source file is empty. Try to export the file."))
  6869. return 'fail'
  6870. try:
  6871. with open(filename, 'w') as file:
  6872. file.writelines('G04*\n')
  6873. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6874. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6875. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6876. file.writelines('G04 Created on : %s*\n' % time_string)
  6877. for line in file_string:
  6878. file.writelines(line)
  6879. except PermissionError:
  6880. self.inform.emit('[WARNING] %s' %
  6881. _("Permission denied, saving not possible.\n"
  6882. "Most likely another app is holding the file open and not accessible."))
  6883. return 'fail'
  6884. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6885. """
  6886. Exports a Excellon Object to an Excellon file.
  6887. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6888. :param filename: Path to the Excellon file to save to.
  6889. :param local_use:
  6890. :param use_thread: if to be run in a separate thread
  6891. :return:
  6892. """
  6893. self.defaults.report_usage("export_excellon()")
  6894. if filename is None:
  6895. if self.defaults["global_last_save_folder"]:
  6896. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6897. else:
  6898. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6899. self.log.debug("export_excellon()")
  6900. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6901. self.defaults["excellon_exp_decimals"]
  6902. )
  6903. if local_use is None:
  6904. try:
  6905. obj = self.collection.get_by_name(str(obj_name))
  6906. except Exception:
  6907. return "Could not retrieve object: %s" % obj_name
  6908. else:
  6909. obj = local_use
  6910. if not isinstance(obj, ExcellonObject):
  6911. self.inform.emit('[ERROR_NOTCL] %s' %
  6912. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6913. return
  6914. # updated units
  6915. eunits = self.defaults["excellon_exp_units"]
  6916. ewhole = self.defaults["excellon_exp_integer"]
  6917. efract = self.defaults["excellon_exp_decimals"]
  6918. ezeros = self.defaults["excellon_exp_zeros"]
  6919. eformat = self.defaults["excellon_exp_format"]
  6920. slot_type = self.defaults["excellon_exp_slot_type"]
  6921. fc_units = self.defaults['units'].upper()
  6922. if fc_units == 'MM':
  6923. factor = 1 if eunits == 'METRIC' else 0.03937
  6924. else:
  6925. factor = 25.4 if eunits == 'METRIC' else 1
  6926. def make_excellon():
  6927. try:
  6928. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6929. header = 'M48\n'
  6930. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6931. (str(self.version), str(self.version_date))
  6932. header += ';Filename: %s' % str(obj_name) + '\n'
  6933. header += ';Created on : %s' % time_str + '\n'
  6934. if eformat == 'dec':
  6935. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6936. header += eunits + '\n'
  6937. for tool in obj.tools:
  6938. if eunits == 'METRIC':
  6939. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6940. tool=str(tool),
  6941. dec=2)
  6942. else:
  6943. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6944. tool=str(tool),
  6945. dec=4)
  6946. else:
  6947. if ezeros == 'LZ':
  6948. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6949. form='ndec', e_zeros='LZ', factor=factor,
  6950. slot_type=slot_type)
  6951. header += '%s,%s\n' % (eunits, 'LZ')
  6952. header += format_exc
  6953. for tool in obj.tools:
  6954. if eunits == 'METRIC':
  6955. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6956. float(obj.tools[tool]['tooldia']) * factor,
  6957. tool=str(tool),
  6958. dec=2)
  6959. else:
  6960. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6961. float(obj.tools[tool]['tooldia']) * factor,
  6962. tool=str(tool),
  6963. dec=4)
  6964. else:
  6965. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6966. form='ndec', e_zeros='TZ', factor=factor,
  6967. slot_type=slot_type)
  6968. header += '%s,%s\n' % (eunits, 'TZ')
  6969. header += format_exc
  6970. for tool in obj.tools:
  6971. if eunits == 'METRIC':
  6972. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6973. float(obj.tools[tool]['tooldia']) * factor,
  6974. tool=str(tool),
  6975. dec=2)
  6976. else:
  6977. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6978. float(obj.tools[tool]['tooldia']) * factor,
  6979. tool=str(tool),
  6980. dec=4)
  6981. header += '%\n'
  6982. footer = 'M30\n'
  6983. exported_excellon = header
  6984. exported_excellon += excellon_code
  6985. exported_excellon += footer
  6986. if local_use is None:
  6987. try:
  6988. with open(filename, 'w') as fp:
  6989. fp.write(exported_excellon)
  6990. except PermissionError:
  6991. self.inform.emit('[WARNING] %s' %
  6992. _("Permission denied, saving not possible.\n"
  6993. "Most likely another app is holding the file open and not accessible."))
  6994. return 'fail'
  6995. if self.defaults["global_open_style"] is False:
  6996. self.file_opened.emit("Excellon", filename)
  6997. self.file_saved.emit("Excellon", filename)
  6998. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6999. else:
  7000. return exported_excellon
  7001. except Exception as e:
  7002. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7003. return 'fail'
  7004. if use_thread is True:
  7005. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7006. def job_thread_exc(app_obj):
  7007. ret = make_excellon()
  7008. if ret == 'fail':
  7009. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7010. return
  7011. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7012. else:
  7013. eret = make_excellon()
  7014. if eret == 'fail':
  7015. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7016. return 'fail'
  7017. if local_use is not None:
  7018. return eret
  7019. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7020. """
  7021. Exports a Gerber Object to an Gerber file.
  7022. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7023. :param filename: Path to the Gerber file to save to.
  7024. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7025. When not None, the value will be the actual Gerber object for which to create
  7026. the Gerber code
  7027. :param use_thread: if to be run in a separate thread
  7028. :return:
  7029. """
  7030. self.defaults.report_usage("export_gerber()")
  7031. if filename is None:
  7032. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7033. is not None else self.defaults["global_last_folder"]
  7034. self.log.debug("export_gerber()")
  7035. if local_use is None:
  7036. try:
  7037. obj = self.collection.get_by_name(str(obj_name))
  7038. except Exception:
  7039. return 'fail'
  7040. else:
  7041. obj = local_use
  7042. # updated units
  7043. gunits = self.defaults["gerber_exp_units"]
  7044. gwhole = self.defaults["gerber_exp_integer"]
  7045. gfract = self.defaults["gerber_exp_decimals"]
  7046. gzeros = self.defaults["gerber_exp_zeros"]
  7047. fc_units = self.defaults['units'].upper()
  7048. if fc_units == 'MM':
  7049. factor = 1 if gunits == 'MM' else 0.03937
  7050. else:
  7051. factor = 25.4 if gunits == 'MM' else 1
  7052. def make_gerber():
  7053. try:
  7054. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7055. header = 'G04*\n'
  7056. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7057. (str(self.version), str(self.version_date))
  7058. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7059. header += 'G04 Created on : %s*' % time_str + '\n'
  7060. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7061. header += "%MO{units}*%\n".format(units=gunits)
  7062. for apid in obj.apertures:
  7063. if obj.apertures[apid]['type'] == 'C':
  7064. header += "%ADD{apid}{type},{size}*%\n".format(
  7065. apid=str(apid),
  7066. type='C',
  7067. size=(factor * obj.apertures[apid]['size'])
  7068. )
  7069. elif obj.apertures[apid]['type'] == 'R':
  7070. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7071. apid=str(apid),
  7072. type='R',
  7073. width=(factor * obj.apertures[apid]['width']),
  7074. height=(factor * obj.apertures[apid]['height'])
  7075. )
  7076. elif obj.apertures[apid]['type'] == 'O':
  7077. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7078. apid=str(apid),
  7079. type='O',
  7080. width=(factor * obj.apertures[apid]['width']),
  7081. height=(factor * obj.apertures[apid]['height'])
  7082. )
  7083. header += '\n'
  7084. # obsolete units but some software may need it
  7085. if gunits == 'IN':
  7086. header += 'G70*\n'
  7087. else:
  7088. header += 'G71*\n'
  7089. # Absolute Mode
  7090. header += 'G90*\n'
  7091. header += 'G01*\n'
  7092. # positive polarity
  7093. header += '%LPD*%\n'
  7094. footer = 'M02*\n'
  7095. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7096. exported_gerber = header
  7097. exported_gerber += gerber_code
  7098. exported_gerber += footer
  7099. if local_use is None:
  7100. try:
  7101. with open(filename, 'w') as fp:
  7102. fp.write(exported_gerber)
  7103. except PermissionError:
  7104. self.inform.emit('[WARNING] %s' %
  7105. _("Permission denied, saving not possible.\n"
  7106. "Most likely another app is holding the file open and not accessible."))
  7107. return 'fail'
  7108. if self.defaults["global_open_style"] is False:
  7109. self.file_opened.emit("Gerber", filename)
  7110. self.file_saved.emit("Gerber", filename)
  7111. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7112. else:
  7113. return exported_gerber
  7114. except Exception as e:
  7115. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7116. return 'fail'
  7117. if use_thread is True:
  7118. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7119. def job_thread_grb(app_obj):
  7120. ret = make_gerber()
  7121. if ret == 'fail':
  7122. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7123. return
  7124. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7125. else:
  7126. gret = make_gerber()
  7127. if gret == 'fail':
  7128. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7129. return 'fail'
  7130. if local_use is not None:
  7131. return gret
  7132. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7133. """
  7134. Exports a Geometry Object to an DXF file.
  7135. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7136. :param filename: Path to the DXF file to save to.
  7137. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7138. When not None, the value will be the actual Geometry object for which to create
  7139. the Geometry/DXF code
  7140. :param use_thread: if to be run in a separate thread
  7141. :return:
  7142. """
  7143. self.defaults.report_usage("export_dxf()")
  7144. if filename is None:
  7145. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7146. is not None else self.defaults["global_last_folder"]
  7147. self.log.debug("export_dxf()")
  7148. if local_use is None:
  7149. try:
  7150. obj = self.collection.get_by_name(str(obj_name))
  7151. except Exception:
  7152. return 'fail'
  7153. else:
  7154. obj = local_use
  7155. def make_dxf():
  7156. try:
  7157. dxf_code = obj.export_dxf()
  7158. if local_use is None:
  7159. try:
  7160. dxf_code.saveas(filename)
  7161. except PermissionError:
  7162. self.inform.emit('[WARNING] %s' %
  7163. _("Permission denied, saving not possible.\n"
  7164. "Most likely another app is holding the file open and not accessible."))
  7165. return 'fail'
  7166. if self.defaults["global_open_style"] is False:
  7167. self.file_opened.emit("DXF", filename)
  7168. self.file_saved.emit("DXF", filename)
  7169. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7170. else:
  7171. return dxf_code
  7172. except Exception as e:
  7173. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7174. return 'fail'
  7175. if use_thread is True:
  7176. with self.proc_container.new(_("Exporting DXF")) as proc:
  7177. def job_thread_exc(app_obj):
  7178. ret_dxf_val = make_dxf()
  7179. if ret_dxf_val == 'fail':
  7180. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7181. return
  7182. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7183. else:
  7184. ret = make_dxf()
  7185. if ret == 'fail':
  7186. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7187. return
  7188. if local_use is not None:
  7189. return ret
  7190. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7191. """
  7192. Adds a new Geometry Object to the projects and populates
  7193. it with shapes extracted from the SVG file.
  7194. :param plot: If True then the resulting object will be plotted on canvas
  7195. :param filename: Path to the SVG file.
  7196. :param geo_type: Type of FlatCAM object that will be created from SVG
  7197. :param outname: The name given to the resulting FlatCAM object
  7198. :return:
  7199. """
  7200. self.defaults.report_usage("import_svg()")
  7201. log.debug("App.import_svg()")
  7202. obj_type = ""
  7203. if geo_type is None or geo_type == "geometry":
  7204. obj_type = "geometry"
  7205. elif geo_type == "gerber":
  7206. obj_type = "gerber"
  7207. else:
  7208. self.inform.emit('[ERROR_NOTCL] %s' %
  7209. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7210. return
  7211. units = self.defaults['units'].upper()
  7212. def obj_init(geo_obj, app_obj):
  7213. geo_obj.import_svg(filename, obj_type, units=units)
  7214. geo_obj.multigeo = False
  7215. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7216. with self.proc_container.new(_("Importing SVG")) as proc:
  7217. # Object name
  7218. name = outname or filename.split('/')[-1].split('\\')[-1]
  7219. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7220. if ret == 'fail':
  7221. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7222. return 'fail'
  7223. # Register recent file
  7224. self.file_opened.emit("svg", filename)
  7225. # appGUI feedback
  7226. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7227. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7228. """
  7229. Adds a new Geometry Object to the projects and populates
  7230. it with shapes extracted from the DXF file.
  7231. :param filename: Path to the DXF file.
  7232. :param geo_type: Type of FlatCAM object that will be created from DXF
  7233. :param outname: Name for the imported Geometry
  7234. :param plot: If True then the resulting object will be plotted on canvas
  7235. :return:
  7236. """
  7237. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7238. obj_type = ""
  7239. if geo_type is None or geo_type == "geometry":
  7240. obj_type = "geometry"
  7241. elif geo_type == "gerber":
  7242. obj_type = geo_type
  7243. else:
  7244. self.inform.emit('[ERROR_NOTCL] %s' %
  7245. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7246. return
  7247. units = self.defaults['units'].upper()
  7248. def obj_init(geo_obj, app_obj):
  7249. if obj_type == "geometry":
  7250. geo_obj.import_dxf_as_geo(filename, units=units)
  7251. elif obj_type == "gerber":
  7252. geo_obj.import_dxf_as_gerber(filename, units=units)
  7253. else:
  7254. return "fail"
  7255. geo_obj.multigeo = True
  7256. with self.proc_container.new(_("Importing DXF")):
  7257. # Object name
  7258. name = outname or filename.split('/')[-1].split('\\')[-1]
  7259. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7260. if ret == 'fail':
  7261. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7262. return 'fail'
  7263. # Register recent file
  7264. self.file_opened.emit("dxf", filename)
  7265. # appGUI feedback
  7266. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7267. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7268. """
  7269. Opens a Gerber file, parses it and creates a new object for
  7270. it in the program. Thread-safe.
  7271. :param outname: Name of the resulting object. None causes the
  7272. name to be that of the file. Str.
  7273. :param filename: Gerber file filename
  7274. :type filename: str
  7275. :param plot: boolean, to plot or not the resulting object
  7276. :param from_tcl: True if run from Tcl Shell
  7277. :return: None
  7278. """
  7279. # How the object should be initialized
  7280. def obj_init(gerber_obj, app_obj):
  7281. assert isinstance(gerber_obj, GerberObject), \
  7282. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7283. # Opening the file happens here
  7284. try:
  7285. gerber_obj.parse_file(filename)
  7286. except IOError:
  7287. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7288. return "fail"
  7289. except ParseError as err:
  7290. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7291. app_obj.log.error(str(err))
  7292. return "fail"
  7293. except Exception as e:
  7294. log.debug("App.open_gerber() --> %s" % str(e))
  7295. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7296. msg += traceback.format_exc()
  7297. app_obj.inform.emit(msg)
  7298. return "fail"
  7299. if gerber_obj.is_empty():
  7300. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7301. _("Object is not Gerber file or empty. Aborting object creation."))
  7302. return "fail"
  7303. App.log.debug("open_gerber()")
  7304. with self.proc_container.new(_("Opening Gerber")):
  7305. # Object name
  7306. name = outname or filename.split('/')[-1].split('\\')[-1]
  7307. # # ## Object creation # ##
  7308. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7309. if ret_val == 'fail':
  7310. if from_tcl:
  7311. filename = self.defaults['global_tcl_path'] + '/' + name
  7312. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7313. if ret_val == 'fail':
  7314. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7315. return 'fail'
  7316. # Register recent file
  7317. self.file_opened.emit("gerber", filename)
  7318. # appGUI feedback
  7319. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7320. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7321. """
  7322. Opens an Excellon file, parses it and creates a new object for
  7323. it in the program. Thread-safe.
  7324. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7325. :param filename: Excellon file filename
  7326. :type filename: str
  7327. :param plot: boolean, to plot or not the resulting object
  7328. :param from_tcl: True if run from Tcl Shell
  7329. :return: None
  7330. """
  7331. App.log.debug("open_excellon()")
  7332. # How the object should be initialized
  7333. def obj_init(excellon_obj, app_obj):
  7334. try:
  7335. ret = excellon_obj.parse_file(filename=filename)
  7336. if ret == "fail":
  7337. log.debug("Excellon parsing failed.")
  7338. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7339. return "fail"
  7340. except IOError:
  7341. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7342. log.debug("Could not open Excellon object.")
  7343. return "fail"
  7344. except Exception:
  7345. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7346. msg += traceback.format_exc()
  7347. app_obj.inform.emit(msg)
  7348. return "fail"
  7349. ret = excellon_obj.create_geometry()
  7350. if ret == 'fail':
  7351. log.debug("Could not create geometry for Excellon object.")
  7352. return "fail"
  7353. for tool in excellon_obj.tools:
  7354. if excellon_obj.tools[tool]['solid_geometry']:
  7355. return
  7356. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7357. return "fail"
  7358. with self.proc_container.new(_("Opening Excellon.")):
  7359. # Object name
  7360. name = outname or filename.split('/')[-1].split('\\')[-1]
  7361. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7362. if ret_val == 'fail':
  7363. if from_tcl:
  7364. filename = self.defaults['global_tcl_path'] + '/' + name
  7365. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7366. if ret_val == 'fail':
  7367. self.inform.emit('[ERROR_NOTCL] %s' %
  7368. _('Open Excellon file failed. Probable not an Excellon file.'))
  7369. return
  7370. # Register recent file
  7371. self.file_opened.emit("excellon", filename)
  7372. # appGUI feedback
  7373. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7374. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7375. """
  7376. Opens a G-gcode file, parses it and creates a new object for
  7377. it in the program. Thread-safe.
  7378. :param filename: G-code file filename
  7379. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7380. :param force_parsing:
  7381. :param plot: If True plot the object on canvas
  7382. :param from_tcl: True if run from Tcl Shell
  7383. :return: None
  7384. """
  7385. App.log.debug("open_gcode()")
  7386. # How the object should be initialized
  7387. def obj_init(job_obj, app_obj_):
  7388. """
  7389. :param job_obj: the resulting object
  7390. :type app_obj_: App
  7391. """
  7392. assert isinstance(app_obj_, App), \
  7393. "Initializer expected App, got %s" % type(app_obj_)
  7394. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7395. try:
  7396. f = open(filename)
  7397. gcode = f.read()
  7398. f.close()
  7399. except IOError:
  7400. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7401. return "fail"
  7402. job_obj.gcode = gcode
  7403. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7404. if gcode_ret == "fail":
  7405. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7406. return "fail"
  7407. job_obj.create_geometry()
  7408. with self.proc_container.new(_("Opening G-Code.")):
  7409. # Object name
  7410. name = outname or filename.split('/')[-1].split('\\')[-1]
  7411. # New object creation and file processing
  7412. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7413. if ret_val == 'fail':
  7414. if from_tcl:
  7415. filename = self.defaults['global_tcl_path'] + '/' + name
  7416. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7417. if ret_val == 'fail':
  7418. self.inform.emit('[ERROR_NOTCL] %s' %
  7419. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7420. "Try to load it from File menu.\n "
  7421. "Attempting to create a FlatCAM CNCJob Object from "
  7422. "G-Code file failed during processing"))
  7423. return "fail"
  7424. # Register recent file
  7425. self.file_opened.emit("cncjob", filename)
  7426. # appGUI feedback
  7427. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7428. def open_hpgl2(self, filename, outname=None):
  7429. """
  7430. Opens a HPGL2 file, parses it and creates a new object for
  7431. it in the program. Thread-safe.
  7432. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7433. :param filename: HPGL2 file filename
  7434. :return: None
  7435. """
  7436. filename = filename
  7437. # How the object should be initialized
  7438. def obj_init(geo_obj, app_obj):
  7439. assert isinstance(geo_obj, GeometryObject), \
  7440. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7441. # Opening the file happens here
  7442. obj = HPGL2(self)
  7443. try:
  7444. HPGL2.parse_file(obj, filename)
  7445. except IOError:
  7446. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7447. return "fail"
  7448. except ParseError as err:
  7449. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7450. app_obj.log.error(str(err))
  7451. return "fail"
  7452. except Exception as e:
  7453. log.debug("App.open_hpgl2() --> %s" % str(e))
  7454. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7455. msg += traceback.format_exc()
  7456. app_obj.inform.emit(msg)
  7457. return "fail"
  7458. geo_obj.multigeo = True
  7459. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7460. geo_obj.tools = deepcopy(obj.tools)
  7461. geo_obj.source_file = deepcopy(obj.source_file)
  7462. del obj
  7463. if not geo_obj.solid_geometry:
  7464. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7465. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7466. return "fail"
  7467. App.log.debug("open_hpgl2()")
  7468. with self.proc_container.new(_("Opening HPGL2")):
  7469. # Object name
  7470. name = outname or filename.split('/')[-1].split('\\')[-1]
  7471. # # ## Object creation # ##
  7472. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7473. if ret == 'fail':
  7474. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7475. return 'fail'
  7476. # Register recent file
  7477. self.file_opened.emit("geometry", filename)
  7478. # appGUI feedback
  7479. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7480. def open_script(self, filename, outname=None, silent=False):
  7481. """
  7482. Opens a Script file, parses it and creates a new object for
  7483. it in the program. Thread-safe.
  7484. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7485. :param filename: Script file filename
  7486. :param silent: If True there will be no messages printed to StatusBar
  7487. :return: None
  7488. """
  7489. def obj_init(script_obj, app_obj):
  7490. assert isinstance(script_obj, ScriptObject), \
  7491. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7492. if silent is False:
  7493. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7494. try:
  7495. script_obj.parse_file(filename)
  7496. except IOError:
  7497. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7498. return "fail"
  7499. except ParseError as err:
  7500. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7501. app_obj.log.error(str(err))
  7502. return "fail"
  7503. except Exception as e:
  7504. log.debug("App.open_script() -> %s" % str(e))
  7505. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7506. msg += traceback.format_exc()
  7507. app_obj.inform.emit(msg)
  7508. return "fail"
  7509. App.log.debug("open_script()")
  7510. with self.proc_container.new(_("Opening TCL Script...")):
  7511. # Object name
  7512. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7513. # Object creation
  7514. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7515. if ret_val == 'fail':
  7516. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7517. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7518. if ret_val == 'fail':
  7519. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7520. return 'fail'
  7521. # Register recent file
  7522. self.file_opened.emit("script", filename)
  7523. # appGUI feedback
  7524. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7525. def open_config_file(self, filename, run_from_arg=None):
  7526. """
  7527. Loads a config file from the specified file.
  7528. :param filename: Name of the file from which to load.
  7529. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7530. :return: None
  7531. """
  7532. App.log.debug("Opening config file: " + filename)
  7533. if run_from_arg:
  7534. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7535. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7536. _("Opening FlatCAM Config file.")),
  7537. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7538. color=QtGui.QColor("gray"))
  7539. # # add the tab if it was closed
  7540. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7541. # # first clear previous text in text editor (if any)
  7542. # self.ui.text_editor_tab.code_editor.clear()
  7543. #
  7544. # # Switch plot_area to CNCJob tab
  7545. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7546. # close the Code editor if already open
  7547. if self.toggle_codeeditor:
  7548. self.on_toggle_code_editor()
  7549. self.on_toggle_code_editor()
  7550. try:
  7551. if filename:
  7552. f = QtCore.QFile(filename)
  7553. if f.open(QtCore.QIODevice.ReadOnly):
  7554. stream = QtCore.QTextStream(f)
  7555. code_edited = stream.readAll()
  7556. self.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  7557. f.close()
  7558. except IOError:
  7559. App.log.error("Failed to open config file: %s" % filename)
  7560. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7561. (_("Failed to open config file"), filename))
  7562. return
  7563. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7564. """
  7565. Loads a project from the specified file.
  7566. 1) Loads and parses file
  7567. 2) Registers the file as recently opened.
  7568. 3) Calls on_file_new()
  7569. 4) Updates options
  7570. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7571. 6) Calls plot_all() if plot=True
  7572. :param filename: Name of the file from which to load.
  7573. :param run_from_arg: True if run for arguments
  7574. :param plot: If True plot all objects in the project
  7575. :param cli: Run from command line
  7576. :param from_tcl: True if run from Tcl Sehll
  7577. :return: None
  7578. """
  7579. App.log.debug("Opening project: " + filename)
  7580. # block autosaving while a project is loaded
  7581. self.block_autosave = True
  7582. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7583. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7584. if cli is None:
  7585. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7586. if run_from_arg:
  7587. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7588. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7589. _("Opening FlatCAM Project file.")),
  7590. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7591. color=QtGui.QColor("gray"))
  7592. # Open and parse an uncompressed Project file
  7593. try:
  7594. f = open(filename, 'r')
  7595. except IOError:
  7596. if from_tcl:
  7597. name = filename.split('/')[-1].split('\\')[-1]
  7598. filename = self.defaults['global_tcl_path'] + '/' + name
  7599. try:
  7600. f = open(filename, 'r')
  7601. except IOError:
  7602. log.error("Failed to open project file: %s" % filename)
  7603. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7604. return
  7605. else:
  7606. log.error("Failed to open project file: %s" % filename)
  7607. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7608. return
  7609. try:
  7610. d = json.load(f, object_hook=dict2obj)
  7611. except Exception as e:
  7612. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7613. (filename, str(e)))
  7614. f.close()
  7615. # Open and parse a compressed Project file
  7616. try:
  7617. with lzma.open(filename) as f:
  7618. file_content = f.read().decode('utf-8')
  7619. d = json.loads(file_content, object_hook=dict2obj)
  7620. except Exception as e:
  7621. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7622. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7623. return
  7624. # Clear the current project
  7625. # # NOT THREAD SAFE # ##
  7626. if run_from_arg is True:
  7627. pass
  7628. elif cli is True:
  7629. self.delete_selection_shape()
  7630. else:
  7631. self.on_file_new()
  7632. # Project options
  7633. self.options.update(d['options'])
  7634. self.project_filename = filename
  7635. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7636. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7637. if cli is None:
  7638. self.set_screen_units(self.options["units"])
  7639. # Re create objects
  7640. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7641. for obj in d['objs']:
  7642. def obj_init(obj_inst, app_inst):
  7643. try:
  7644. obj_inst.from_dict(obj)
  7645. except Exception as e:
  7646. print('App.open_project() --> ' + str(e))
  7647. return 'fail'
  7648. App.log.debug("Recreating from opened project an %s object: %s" %
  7649. (obj['kind'].capitalize(), obj['options']['name']))
  7650. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7651. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7652. if cli is None:
  7653. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7654. obj['kind'].upper(),
  7655. obj['options']['name']
  7656. )
  7657. )
  7658. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7659. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7660. self.should_we_save = False
  7661. self.file_opened.emit("project", filename)
  7662. # restore autosaving after a project was loaded
  7663. self.block_autosave = False
  7664. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7665. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7666. if cli is None:
  7667. self.set_ui_title(name=self.project_filename)
  7668. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7669. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7670. """
  7671. Re-generates all plots from all objects.
  7672. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7673. :param muted: if True don't print messages
  7674. :param use_thread: if True will use threading for plotting the objects
  7675. :return: None
  7676. """
  7677. self.log.debug("Plot_all()")
  7678. if muted is not True:
  7679. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7680. for plot_obj in self.collection.get_list():
  7681. def worker_task(obj):
  7682. with self.proc_container.new("Plotting"):
  7683. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7684. if fit_view is True:
  7685. self.app_obj.object_plotted.emit(obj)
  7686. if use_thread is True:
  7687. # Send to worker
  7688. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7689. else:
  7690. worker_task(plot_obj)
  7691. def register_folder(self, filename):
  7692. """
  7693. Register the last folder used by the app to open something
  7694. :param filename: the last folder is extracted from the filename
  7695. :return: None
  7696. """
  7697. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7698. def register_save_folder(self, filename):
  7699. """
  7700. Register the last folder used by the app to save something
  7701. :param filename: the last folder is extracted from the filename
  7702. :return: None
  7703. """
  7704. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7705. # def set_progress_bar(self, percentage, text=""):
  7706. # """
  7707. # Set a progress bar to a value (percentage)
  7708. #
  7709. # :param percentage: Value set to the progressbar
  7710. # :param text: Not used
  7711. # :return: None
  7712. # """
  7713. # self.ui.progress_bar.setValue(int(percentage))
  7714. def setup_recent_items(self):
  7715. """
  7716. Setup a dictionary with the recent files accessed, organized by type
  7717. :return:
  7718. """
  7719. icons = {
  7720. "gerber": self.resource_location + "/flatcam_icon16.png",
  7721. "excellon": self.resource_location + "/drill16.png",
  7722. 'geometry': self.resource_location + "/geometry16.png",
  7723. "cncjob": self.resource_location + "/cnc16.png",
  7724. "script": self.resource_location + "/script_new24.png",
  7725. "document": self.resource_location + "/notes16_1.png",
  7726. "project": self.resource_location + "/project16.png",
  7727. "svg": self.resource_location + "/geometry16.png",
  7728. "dxf": self.resource_location + "/dxf16.png",
  7729. "pdf": self.resource_location + "/pdf32.png",
  7730. "image": self.resource_location + "/image16.png"
  7731. }
  7732. try:
  7733. image_opener = self.image_tool.import_image
  7734. except AttributeError:
  7735. image_opener = None
  7736. openers = {
  7737. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7738. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7739. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7740. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7741. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7742. "document": None,
  7743. 'project': self.open_project,
  7744. 'svg': self.import_svg,
  7745. 'dxf': self.import_dxf,
  7746. 'image': image_opener,
  7747. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7748. }
  7749. # Open recent file for files
  7750. try:
  7751. f = open(self.data_path + '/recent.json')
  7752. except IOError:
  7753. App.log.error("Failed to load recent item list.")
  7754. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7755. return
  7756. try:
  7757. self.recent = json.load(f)
  7758. except json.errors.JSONDecodeError:
  7759. App.log.error("Failed to parse recent item list.")
  7760. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7761. f.close()
  7762. return
  7763. f.close()
  7764. # Open recent file for projects
  7765. try:
  7766. fp = open(self.data_path + '/recent_projects.json')
  7767. except IOError:
  7768. App.log.error("Failed to load recent project item list.")
  7769. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7770. return
  7771. try:
  7772. self.recent_projects = json.load(fp)
  7773. except json.errors.JSONDecodeError:
  7774. App.log.error("Failed to parse recent project item list.")
  7775. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7776. fp.close()
  7777. return
  7778. fp.close()
  7779. # Closure needed to create callbacks in a loop.
  7780. # Otherwise late binding occurs.
  7781. def make_callback(func, fname):
  7782. def opener():
  7783. func(fname)
  7784. return opener
  7785. def reset_recent_files():
  7786. # Reset menu
  7787. self.ui.recent.clear()
  7788. self.recent = []
  7789. try:
  7790. ff = open(self.data_path + '/recent.json', 'w')
  7791. except IOError:
  7792. App.log.error("Failed to open recent items file for writing.")
  7793. return
  7794. json.dump(self.recent, ff)
  7795. def reset_recent_projects():
  7796. # Reset menu
  7797. self.ui.recent_projects.clear()
  7798. self.recent_projects = []
  7799. try:
  7800. frp = open(self.data_path + '/recent_projects.json', 'w')
  7801. except IOError:
  7802. App.log.error("Failed to open recent projects items file for writing.")
  7803. return
  7804. json.dump(self.recent, frp)
  7805. # Reset menu
  7806. self.ui.recent.clear()
  7807. self.ui.recent_projects.clear()
  7808. # Create menu items for projects
  7809. for recent in self.recent_projects:
  7810. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7811. if recent['kind'] == 'project':
  7812. try:
  7813. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7814. # Attach callback
  7815. o = make_callback(openers[recent["kind"]], recent['filename'])
  7816. action.triggered.connect(o)
  7817. self.ui.recent_projects.addAction(action)
  7818. except KeyError:
  7819. App.log.error("Unsupported file type: %s" % recent["kind"])
  7820. # Last action in Recent Files menu is one that Clear the content
  7821. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7822. (_("Clear Recent projects")), self)
  7823. clear_action_proj.triggered.connect(reset_recent_projects)
  7824. self.ui.recent_projects.addSeparator()
  7825. self.ui.recent_projects.addAction(clear_action_proj)
  7826. # Create menu items for files
  7827. for recent in self.recent:
  7828. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7829. if recent['kind'] != 'project':
  7830. try:
  7831. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7832. # Attach callback
  7833. o = make_callback(openers[recent["kind"]], recent['filename'])
  7834. action.triggered.connect(o)
  7835. self.ui.recent.addAction(action)
  7836. except KeyError:
  7837. App.log.error("Unsupported file type: %s" % recent["kind"])
  7838. # Last action in Recent Files menu is one that Clear the content
  7839. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7840. (_("Clear Recent files")), self)
  7841. clear_action.triggered.connect(reset_recent_files)
  7842. self.ui.recent.addSeparator()
  7843. self.ui.recent.addAction(clear_action)
  7844. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7845. # self.ui.menufilerecent.set_submenu(recent_menu)
  7846. # recent_menu.show_all()
  7847. # self.ui.recent.show()
  7848. self.log.debug("Recent items list has been populated.")
  7849. def setup_component_editor(self):
  7850. """
  7851. Default text for the Selected tab when is not taken by the Object UI.
  7852. :return:
  7853. """
  7854. # label = QtWidgets.QLabel("Choose an item from Project")
  7855. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7856. sel_title = QtWidgets.QTextEdit(
  7857. _('<b>Shortcut Key List</b>'))
  7858. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7859. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7860. f_settings = QSettings("Open Source", "FlatCAM")
  7861. if f_settings.contains("notebook_font_size"):
  7862. fsize = f_settings.value('notebook_font_size', type=int)
  7863. else:
  7864. fsize = 12
  7865. tsize = fsize + int(fsize / 2)
  7866. # selected_text = (_('''
  7867. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7868. # </p>
  7869. #
  7870. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7871. # The normal flow when working in FlatCAM is the following:</span></p>
  7872. #
  7873. # <ol>
  7874. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7875. # file into
  7876. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7877. # even dragging and dropping the files on the appGUI.<br />
  7878. # <br />
  7879. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7880. # drop of the
  7881. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7882. # &nbsp;</li>
  7883. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7884. # and then
  7885. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7886. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7887. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7888. # <br />
  7889. # If the selection of the object is done on the canvas by single click instead, and the
  7890. # <strong>SELECTED TAB</strong>
  7891. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7892. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7893. # it even if it was out of focus.<br />
  7894. # <br />
  7895. # You can change the parameters in this screen and the flow direction is like this:<br />
  7896. # <br />
  7897. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7898. # <strong> Geometry Object
  7899. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7900. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7901. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7902. # </ol>
  7903. #
  7904. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7905. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7906. # <strong>F3</strong>.</span></p>
  7907. #
  7908. # ''').format(fsize=fsize, tsize=tsize))
  7909. selected_text = '''
  7910. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7911. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7912. {s1}</span></p>
  7913. <ol>
  7914. <li><span style="font-size:{fsize}px">{s2}<br />
  7915. <br />
  7916. {s3}</span><br />
  7917. &nbsp;</li>
  7918. <li><span style="font-size:{fsize}px">{s4}<br />
  7919. &nbsp;</li>
  7920. <br />
  7921. <li><span style="font-size:{fsize}px">{s5}<br />
  7922. &nbsp;</li>
  7923. <br />
  7924. <li><span style="font-size:{fsize}px">{s6}<br />
  7925. <br />
  7926. {s7}</span></li>
  7927. </ol>
  7928. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7929. '''.format(
  7930. title=_("Selected Tab - Choose an Item from Project Tab"),
  7931. subtitle=_("Details"),
  7932. s1=_("The normal flow when working with the application is the following:"),
  7933. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7934. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7935. "files on the GUI."),
  7936. s3=_("You can also load a project by double clicking on the project file, "
  7937. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7938. "actions offered within the app."),
  7939. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7940. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7941. "SELECTED TAB will be updated with the object properties according to its kind: "
  7942. "Gerber, Excellon, Geometry or CNCJob object."),
  7943. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7944. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7945. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7946. "the SELECTED TAB and populate it even if it was out of focus."),
  7947. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7948. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7949. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7950. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7951. "(again, done in SELECTED TAB) --> Save GCode."),
  7952. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7953. "or through its own key shortcut: <b>F3</b>."),
  7954. tsize=tsize,
  7955. fsize=fsize
  7956. )
  7957. sel_title.setText(selected_text)
  7958. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7959. self.ui.selected_scroll_area.setWidget(sel_title)
  7960. def setup_obj_classes(self):
  7961. """
  7962. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7963. class.
  7964. :return: None
  7965. """
  7966. FlatCAMObj.app = self
  7967. ObjectCollection.app = self
  7968. Gerber.app = self
  7969. Excellon.app = self
  7970. Geometry.app = self
  7971. CNCjob.app = self
  7972. FCProcess.app = self
  7973. FCProcessContainer.app = self
  7974. OptionsGroupUI.app = self
  7975. def version_check(self):
  7976. """
  7977. Checks for the latest version of the program. Alerts the
  7978. user if theirs is outdated. This method is meant to be run
  7979. in a separate thread.
  7980. :return: None
  7981. """
  7982. self.log.debug("version_check()")
  7983. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7984. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7985. App.version_url,
  7986. str(self.defaults['global_serial']),
  7987. str(self.version),
  7988. str(self.os),
  7989. urllib.parse.urlencode(self.defaults["global_stats"])
  7990. )
  7991. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7992. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7993. # urllib.parse.urlencode(self.defaults["global_stats"])
  7994. else:
  7995. # no_stats dict; just so it won't break things on website
  7996. no_ststs_dict = {}
  7997. no_ststs_dict["global_ststs"] = {}
  7998. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7999. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8000. App.log.debug("Checking for updates @ %s" % full_url)
  8001. # ## Get the data
  8002. try:
  8003. f = urllib.request.urlopen(full_url)
  8004. except Exception:
  8005. # App.log.warning("Failed checking for latest version. Could not connect.")
  8006. self.log.warning("Failed checking for latest version. Could not connect.")
  8007. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8008. return
  8009. try:
  8010. data = json.load(f)
  8011. except Exception as e:
  8012. App.log.error("Could not parse information about latest version.")
  8013. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8014. App.log.debug("json.load(): %s" % str(e))
  8015. f.close()
  8016. return
  8017. f.close()
  8018. # ## Latest version?
  8019. if self.version >= data["version"]:
  8020. App.log.debug("FlatCAM is up to date!")
  8021. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8022. return
  8023. App.log.debug("Newer version available.")
  8024. self.message.emit(
  8025. _("Newer Version Available"),
  8026. '%s<br><br>><b>%s</b><br>%s' % (
  8027. _("There is a newer version of FlatCAM available for download:"),
  8028. str(data["name"]),
  8029. str(data["message"])
  8030. ),
  8031. _("info")
  8032. )
  8033. def on_plotcanvas_setup(self, container=None):
  8034. """
  8035. This is doing the setup for the plot area (canvas).
  8036. :param container: QT Widget where to install the canvas
  8037. :return: None
  8038. """
  8039. if container:
  8040. plot_container = container
  8041. else:
  8042. plot_container = self.ui.right_layout
  8043. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8044. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8045. self.is_legacy = True
  8046. self.defaults["global_graphic_engine"] = "2D"
  8047. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8048. else:
  8049. try:
  8050. self.plotcanvas = PlotCanvas(plot_container, self)
  8051. except Exception as er:
  8052. msg_txt = traceback.format_exc()
  8053. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8054. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8055. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8056. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8057. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8058. msg += msg_txt
  8059. self.inform.emit(msg)
  8060. return 'fail'
  8061. # So it can receive key presses
  8062. self.plotcanvas.native.setFocus()
  8063. if self.is_legacy is False:
  8064. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8065. # Set the mouse button for panning
  8066. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8067. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8068. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8069. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8070. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8071. # Keys over plot enabled
  8072. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8073. if self.defaults['global_cursor_type'] == 'small':
  8074. self.app_cursor = self.plotcanvas.new_cursor()
  8075. else:
  8076. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8077. if self.ui.grid_snap_btn.isChecked():
  8078. self.app_cursor.enabled = True
  8079. else:
  8080. self.app_cursor.enabled = False
  8081. if self.is_legacy is False:
  8082. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8083. else:
  8084. # will use the default Matplotlib axes
  8085. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8086. def on_zoom_fit(self):
  8087. """
  8088. Callback for zoom-fit request. This can be either from the corresponding
  8089. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8090. with axes limits from the geometry bounds of all objects.
  8091. :return: None
  8092. """
  8093. if self.is_legacy is False:
  8094. self.plotcanvas.fit_view()
  8095. else:
  8096. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8097. width = xmax - xmin
  8098. height = ymax - ymin
  8099. xmin -= 0.05 * width
  8100. xmax += 0.05 * width
  8101. ymin -= 0.05 * height
  8102. ymax += 0.05 * height
  8103. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8104. def on_zoom_in(self):
  8105. """
  8106. Callback for zoom-in request.
  8107. :return:
  8108. """
  8109. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8110. def on_zoom_out(self):
  8111. """
  8112. Callback for zoom-out request.
  8113. :return:
  8114. """
  8115. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8116. def disable_all_plots(self):
  8117. self.defaults.report_usage("disable_all_plots()")
  8118. self.disable_plots(self.collection.get_list())
  8119. self.inform.emit('[success] %s' %
  8120. _("All plots disabled."))
  8121. def disable_other_plots(self):
  8122. self.defaults.report_usage("disable_other_plots()")
  8123. self.disable_plots(self.collection.get_non_selected())
  8124. self.inform.emit('[success] %s' %
  8125. _("All non selected plots disabled."))
  8126. def enable_all_plots(self):
  8127. self.defaults.report_usage("enable_all_plots()")
  8128. self.enable_plots(self.collection.get_list())
  8129. self.inform.emit('[success] %s' %
  8130. _("All plots enabled."))
  8131. def on_enable_sel_plots(self):
  8132. log.debug("App.on_enable_sel_plot()")
  8133. object_list = self.collection.get_selected()
  8134. self.enable_plots(objects=object_list)
  8135. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8136. def on_disable_sel_plots(self):
  8137. log.debug("App.on_disable_sel_plot()")
  8138. # self.inform.emit(_("Disabling plots ..."))
  8139. object_list = self.collection.get_selected()
  8140. self.disable_plots(objects=object_list)
  8141. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8142. def enable_plots(self, objects):
  8143. """
  8144. Enable plots
  8145. :param objects: list of Objects to be enabled
  8146. :return:
  8147. """
  8148. log.debug("Enabling plots ...")
  8149. # self.inform.emit(_("Working ..."))
  8150. for obj in objects:
  8151. if obj.options['plot'] is False:
  8152. obj.options.set_change_callback(lambda x: None)
  8153. obj.options['plot'] = True
  8154. try:
  8155. # only the Gerber obj has on_plot_cb_click() method
  8156. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8157. # disable this cb while disconnected,
  8158. # in case the operation takes time the user is not allowed to change it
  8159. obj.ui.plot_cb.setDisabled(True)
  8160. except AttributeError:
  8161. pass
  8162. obj.set_form_item("plot")
  8163. try:
  8164. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8165. obj.ui.plot_cb.setDisabled(False)
  8166. except AttributeError:
  8167. pass
  8168. obj.options.set_change_callback(obj.on_options_change)
  8169. def worker_task(objs):
  8170. with self.proc_container.new(_("Enabling plots ...")):
  8171. for plot_obj in objs:
  8172. # obj.options['plot'] = True
  8173. if isinstance(plot_obj, CNCJobObject):
  8174. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8175. else:
  8176. plot_obj.plot(visible=True)
  8177. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8178. def disable_plots(self, objects):
  8179. """
  8180. Disables plots
  8181. :param objects: list of Objects to be disabled
  8182. :return:
  8183. """
  8184. # if no objects selected then do nothing
  8185. if not self.collection.get_selected():
  8186. return
  8187. log.debug("Disabling plots ...")
  8188. # self.inform.emit(_("Working ..."))
  8189. for obj in objects:
  8190. if obj.options['plot'] is True:
  8191. obj.options.set_change_callback(lambda x: None)
  8192. obj.options['plot'] = False
  8193. try:
  8194. # only the Gerber obj has on_plot_cb_click() method
  8195. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8196. obj.ui.plot_cb.setDisabled(True)
  8197. except AttributeError:
  8198. pass
  8199. obj.set_form_item("plot")
  8200. try:
  8201. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8202. obj.ui.plot_cb.setDisabled(False)
  8203. except AttributeError:
  8204. pass
  8205. obj.options.set_change_callback(obj.on_options_change)
  8206. try:
  8207. self.delete_selection_shape()
  8208. except Exception as e:
  8209. log.debug("App.disable_plots() --> %s" % str(e))
  8210. def worker_task(objs):
  8211. with self.proc_container.new(_("Disabling plots ...")):
  8212. for plot_obj in objs:
  8213. # obj.options['plot'] = True
  8214. if isinstance(plot_obj, CNCJobObject):
  8215. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8216. else:
  8217. plot_obj.plot(visible=False)
  8218. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8219. def toggle_plots(self, objects):
  8220. """
  8221. Toggle plots visibility
  8222. :param objects: list of Objects for which to be toggled the visibility
  8223. :return: None
  8224. """
  8225. # if no objects selected then do nothing
  8226. if not self.collection.get_selected():
  8227. return
  8228. log.debug("Toggling plots ...")
  8229. self.inform.emit(_("Working ..."))
  8230. for obj in objects:
  8231. if obj.options['plot'] is False:
  8232. obj.options['plot'] = True
  8233. else:
  8234. obj.options['plot'] = False
  8235. self.app_obj.plots_updated.emit()
  8236. def clear_plots(self):
  8237. """
  8238. Clear the plots
  8239. :return: None
  8240. """
  8241. objects = self.collection.get_list()
  8242. for obj in objects:
  8243. obj.clear(obj == objects[-1])
  8244. # Clear pool to free memory
  8245. self.clear_pool()
  8246. def on_set_color_action_triggered(self):
  8247. """
  8248. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8249. :return:
  8250. """
  8251. new_color = self.defaults['gerber_plot_fill']
  8252. clicked_action = self.sender()
  8253. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8254. act_name = clicked_action.text()
  8255. sel_obj_list = self.collection.get_selected()
  8256. if not sel_obj_list:
  8257. return
  8258. # a default value, I just chose this one
  8259. alpha_level = 'BF'
  8260. for sel_obj in sel_obj_list:
  8261. if sel_obj.kind == 'excellon':
  8262. alpha_level = str(hex(
  8263. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8264. elif sel_obj.kind == 'gerber':
  8265. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8266. elif sel_obj.kind == 'geometry':
  8267. alpha_level = 'FF'
  8268. else:
  8269. log.debug(
  8270. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8271. continue
  8272. sel_obj.alpha_level = alpha_level
  8273. if act_name == _('Red'):
  8274. new_color = '#FF0000' + alpha_level
  8275. if act_name == _('Blue'):
  8276. new_color = '#0000FF' + alpha_level
  8277. if act_name == _('Yellow'):
  8278. new_color = '#FFDF00' + alpha_level
  8279. if act_name == _('Green'):
  8280. new_color = '#00FF00' + alpha_level
  8281. if act_name == _('Purple'):
  8282. new_color = '#FF00FF' + alpha_level
  8283. if act_name == _('Brown'):
  8284. new_color = '#A52A2A' + alpha_level
  8285. if act_name == _('White'):
  8286. new_color = '#FFFFFF' + alpha_level
  8287. if act_name == _('Black'):
  8288. new_color = '#000000' + alpha_level
  8289. if act_name == _('Custom'):
  8290. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8291. c_dialog = QtWidgets.QColorDialog()
  8292. plot_fill_color = c_dialog.getColor(initial=new_color)
  8293. if plot_fill_color.isValid() is False:
  8294. return
  8295. new_color = str(plot_fill_color.name()) + alpha_level
  8296. if act_name == _("Default"):
  8297. for sel_obj in sel_obj_list:
  8298. if sel_obj.kind == 'excellon':
  8299. new_color = self.defaults['excellon_plot_fill']
  8300. new_line_color = self.defaults['excellon_plot_line']
  8301. elif sel_obj.kind == 'gerber':
  8302. new_color = self.defaults['gerber_plot_fill']
  8303. new_line_color = self.defaults['gerber_plot_line']
  8304. elif sel_obj.kind == 'geometry':
  8305. new_color = self.defaults['geometry_plot_line']
  8306. new_line_color = self.defaults['geometry_plot_line']
  8307. else:
  8308. log.debug(
  8309. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8310. continue
  8311. sel_obj.fill_color = new_color
  8312. sel_obj.outline_color = new_line_color
  8313. sel_obj.shapes.redraw(
  8314. update_colors=(new_color, new_line_color)
  8315. )
  8316. return
  8317. if act_name == _("Opacity"):
  8318. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8319. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8320. if ok_button:
  8321. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8322. for sel_obj in sel_obj_list:
  8323. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8324. sel_obj.shapes.redraw(
  8325. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8326. )
  8327. return
  8328. new_line_color = color_variant(new_color[:7], 0.7)
  8329. if act_name == _("White"):
  8330. new_line_color = color_variant("#dedede", 0.7)
  8331. for sel_obj in sel_obj_list:
  8332. sel_obj.fill_color = new_color
  8333. sel_obj.outline_color = new_line_color
  8334. sel_obj.shapes.redraw(
  8335. update_colors=(new_color, new_line_color)
  8336. )
  8337. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  8338. group = self.collection.group_items["gerber"]
  8339. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  8340. new_c = (new_line_color, new_color)
  8341. for sel_obj in sel_obj_list:
  8342. if sel_obj.kind == 'gerber':
  8343. item = sel_obj.item
  8344. item_index = self.collection.index(item.row(), 0, group_index)
  8345. idx = item_index.row()
  8346. self.defaults["gerber_color_list"][idx] = new_c
  8347. def generate_cnc_job(self, objects):
  8348. """
  8349. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8350. :param objects: Selected objects in the Project Tab
  8351. :return:
  8352. """
  8353. self.defaults.report_usage("generate_cnc_job()")
  8354. # for obj in objects:
  8355. # obj.generatecncjob()
  8356. for obj in objects:
  8357. obj.on_generatecnc_button_click()
  8358. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8359. """
  8360. Saves the current project to the specified file.
  8361. :param filename: Name of the file in which to save.
  8362. :type filename: str
  8363. :param quit_action: if the project saving will be followed by an app quit; boolean
  8364. :param silent: if True will not display status messages
  8365. :param from_tcl True is run from Tcl Shell
  8366. :return: None
  8367. """
  8368. self.log.debug("save_project()")
  8369. self.save_in_progress = True
  8370. with self.proc_container.new(_("Saving FlatCAM Project")):
  8371. # Capture the latest changes
  8372. # Current object
  8373. try:
  8374. current_object = self.collection.get_active()
  8375. if current_object:
  8376. current_object.read_form()
  8377. except Exception as e:
  8378. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8379. pass
  8380. # Serialize the whole project
  8381. d = {
  8382. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8383. "options": self.options,
  8384. "version": self.version
  8385. }
  8386. if self.defaults["global_save_compressed"] is True:
  8387. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8388. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8389. # # Write
  8390. f.write(g)
  8391. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8392. else:
  8393. # Open file
  8394. try:
  8395. f = open(filename, 'w')
  8396. except IOError:
  8397. App.log.error("Failed to open file for saving: %s", filename)
  8398. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8399. return
  8400. # Write
  8401. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8402. f.close()
  8403. # verification of the saved project
  8404. # Open and parse
  8405. try:
  8406. saved_f = open(filename, 'r')
  8407. except IOError:
  8408. if silent is False:
  8409. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8410. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8411. return
  8412. try:
  8413. saved_d = json.load(saved_f, object_hook=dict2obj)
  8414. except Exception:
  8415. if silent is False:
  8416. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8417. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8418. f.close()
  8419. return
  8420. saved_f.close()
  8421. if silent is False:
  8422. if 'version' in saved_d:
  8423. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8424. else:
  8425. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8426. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8427. tb_settings = QSettings("Open Source", "FlatCAM")
  8428. lock_state = self.ui.lock_action.isChecked()
  8429. tb_settings.setValue('toolbar_lock', lock_state)
  8430. # This will write the setting to the platform specific storage.
  8431. del tb_settings
  8432. # if quit:
  8433. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8434. # t.start()
  8435. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8436. def start_delayed_quit(self, delay, filename, should_quit=None):
  8437. """
  8438. :param delay: period of checking if project file size is more than zero; in seconds
  8439. :param filename: the name of the project file to be checked periodically for size more than zero
  8440. :param should_quit: if the task finished will be followed by an app quit; boolean
  8441. :return:
  8442. """
  8443. to_quit = should_quit
  8444. self.save_timer = QtCore.QTimer()
  8445. self.save_timer.setInterval(delay)
  8446. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8447. self.save_timer.start()
  8448. def check_project_file_size(self, filename, should_quit=None):
  8449. """
  8450. :param filename: the name of the project file to be checked periodically for size more than zero
  8451. :param should_quit: will quit the app if True; boolean
  8452. :return:
  8453. """
  8454. try:
  8455. if os.stat(filename).st_size > 0:
  8456. self.save_in_progress = False
  8457. self.save_timer.stop()
  8458. if should_quit:
  8459. self.app_quit.emit()
  8460. except Exception:
  8461. traceback.print_exc()
  8462. def save_project_auto(self):
  8463. """
  8464. Called periodically to save the project.
  8465. 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
  8466. # progress.
  8467. :return:
  8468. """
  8469. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8470. self.on_file_saveproject()
  8471. def save_project_auto_update(self):
  8472. """
  8473. Update the auto save time interval value.
  8474. :return:
  8475. """
  8476. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8477. try:
  8478. if self.autosave_timer.isActive():
  8479. self.autosave_timer.stop()
  8480. except Exception:
  8481. pass
  8482. if self.defaults['global_autosave'] is True:
  8483. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8484. self.autosave_timer.start()
  8485. def on_options_app2project(self):
  8486. """
  8487. Callback for Options->Transfer Options->App=>Project. Copies options
  8488. from application defaults to project defaults.
  8489. :return: None
  8490. """
  8491. self.defaults.report_usage("on_options_app2project")
  8492. self.preferencesUiManager.defaults_read_form()
  8493. self.options.update(self.defaults)
  8494. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8495. """
  8496. Shows a message on the FlatCAM Shell
  8497. :param msg: Message to display.
  8498. :param show: Opens the shell.
  8499. :param error: Shows the message as an error.
  8500. :param warning: Shows the message as an warning.
  8501. :param success: Shows the message as an success.
  8502. :param selected: Indicate that something was selected on canvas
  8503. :return: None
  8504. """
  8505. if show:
  8506. self.ui.shell_dock.show()
  8507. try:
  8508. if error:
  8509. self.shell.append_error(msg + "\n")
  8510. elif warning:
  8511. self.shell.append_warning(msg + "\n")
  8512. elif success:
  8513. self.shell.append_success(msg + "\n")
  8514. elif selected:
  8515. self.shell.append_selected(msg + "\n")
  8516. else:
  8517. self.shell.append_output(msg + "\n")
  8518. except AttributeError:
  8519. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8520. def dec_format(self, val, dec=None):
  8521. """
  8522. Returns a formatted float value with a certain number of decimals
  8523. """
  8524. dec_nr = dec if dec is not None else self.decimals
  8525. return float('%.*f' % (dec_nr, val))
  8526. class ArgsThread(QtCore.QObject):
  8527. open_signal = pyqtSignal(list)
  8528. start = pyqtSignal()
  8529. stop = pyqtSignal()
  8530. if sys.platform == 'win32':
  8531. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8532. else:
  8533. address = ('/tmp/testipc', 'AF_UNIX')
  8534. def __init__(self):
  8535. super().__init__()
  8536. self.listener = None
  8537. self.thread_exit = False
  8538. self.start.connect(self.run)
  8539. self.stop.connect(self.close_listener)
  8540. def my_loop(self, address):
  8541. try:
  8542. self.listener = Listener(*address)
  8543. while self.thread_exit is False:
  8544. conn = self.listener.accept()
  8545. self.serve(conn)
  8546. except socket.error:
  8547. try:
  8548. conn = Client(*address)
  8549. conn.send(sys.argv)
  8550. conn.send('close')
  8551. # close the current instance only if there are args
  8552. if len(sys.argv) > 1:
  8553. try:
  8554. self.listener.close()
  8555. except Exception:
  8556. pass
  8557. sys.exit()
  8558. except ConnectionRefusedError:
  8559. if sys.platform == 'win32':
  8560. pass
  8561. else:
  8562. os.system('rm /tmp/testipc')
  8563. self.listener = Listener(*address)
  8564. while True:
  8565. conn = self.listener.accept()
  8566. self.serve(conn)
  8567. def serve(self, conn):
  8568. while self.thread_exit is False:
  8569. msg = conn.recv()
  8570. if msg == 'close':
  8571. break
  8572. self.open_signal.emit(msg)
  8573. conn.close()
  8574. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8575. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8576. @pyqtSlot()
  8577. def run(self):
  8578. self.my_loop(self.address)
  8579. @pyqtSlot()
  8580. def close_listener(self):
  8581. self.thread_exit = True
  8582. self.listener.close()
  8583. # end of file